/*
|--------------------------------------------------------------------------
| SMI Student Gateway
| Main JavaScript File
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| Toast Notification
|--------------------------------------------------------------------------
*/

function showToast(message, type = 'success') {

    const toast = document.createElement('div');

    toast.className =
        'smi-toast smi-toast-' + type;

    toast.innerHTML = message;

    document.body.appendChild(toast);

    setTimeout(() => {

        toast.classList.add('show');

    }, 100);

    setTimeout(() => {

        toast.classList.remove('show');

        setTimeout(() => {

            toast.remove();

        }, 300);

    }, 4000);
}

/*
|--------------------------------------------------------------------------
| Auto Confirm
|--------------------------------------------------------------------------
*/

document.addEventListener('DOMContentLoaded', () => {

    document
    .querySelectorAll('[data-confirm]')
    .forEach(element => {

        element.addEventListener('click', event => {

            const message =
                element.dataset.confirm ||
                'Are you sure?';

            if (!confirm(message)) {

                event.preventDefault();
            }
        });
    });
});

/*
|--------------------------------------------------------------------------
| Auto Focus
|--------------------------------------------------------------------------
*/

document.addEventListener('DOMContentLoaded', () => {

    const firstInput =
        document.querySelector(
            'input, textarea, select'
        );

    if (firstInput) {

        firstInput.focus();
    }
});

/*
|--------------------------------------------------------------------------
| Loading Buttons
|--------------------------------------------------------------------------
*/

document.addEventListener('DOMContentLoaded', () => {

    document
    .querySelectorAll('form')
    .forEach(form => {

        form.addEventListener('submit', () => {

            const button =
                form.querySelector(
                    'button[type="submit"]'
                );

            if (button) {

                button.dataset.original =
                    button.innerHTML;

                button.disabled = true;

                button.innerHTML =
                    'Please wait...';
            }
        });
    });
});

/*
|--------------------------------------------------------------------------
| AJAX Save Attendance
|--------------------------------------------------------------------------
*/

async function saveAttendance(data) {

    try {

        const response =
            await fetch(
                '../ajax/save-attendance.php',
                {
                    method:'POST',
                    body:data
                }
            );

        const result =
            await response.json();

        if (result.success) {

            showToast(
                result.message,
                'success'
            );

        } else {

            showToast(
                result.message,
                'danger'
            );
        }

        return result;

    } catch(error) {

        showToast(
            'Connection error.',
            'danger'
        );

        return false;
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Save Grade
|--------------------------------------------------------------------------
*/

async function saveGrade(data) {

    try {

        const response =
            await fetch(
                '../ajax/save-grade.php',
                {
                    method:'POST',
                    body:data
                }
            );

        const result =
            await response.json();

        if (result.success) {

            showToast(
                result.message,
                'success'
            );

        } else {

            showToast(
                result.message,
                'danger'
            );
        }

        return result;

    } catch(error) {

        showToast(
            'Connection error.',
            'danger'
        );

        return false;
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Homework Submit
|--------------------------------------------------------------------------
*/

async function submitHomework(data) {

    try {

        const response =
            await fetch(
                '../ajax/submit-homework.php',
                {
                    method:'POST',
                    body:data
                }
            );

        const result =
            await response.json();

        if (result.success) {

            showToast(
                result.message,
                'success'
            );

        } else {

            showToast(
                result.message,
                'danger'
            );
        }

        return result;

    } catch(error) {

        showToast(
            'Connection error.',
            'danger'
        );

        return false;
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Shadowing Submit
|--------------------------------------------------------------------------
*/

async function submitShadowing(data) {

    try {

        const response =
            await fetch(
                '../ajax/submit-shadowing.php',
                {
                    method:'POST',
                    body:data
                }
            );

        const result =
            await response.json();

        if (result.success) {

            showToast(
                result.message,
                'success'
            );

        } else {

            showToast(
                result.message,
                'danger'
            );
        }

        return result;

    } catch(error) {

        showToast(
            'Connection error.',
            'danger'
        );

        return false;
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Obstacle Submit
|--------------------------------------------------------------------------
*/

async function submitObstacle(data) {

    try {

        const response =
            await fetch(
                '../ajax/submit-obstacle.php',
                {
                    method:'POST',
                    body:data
                }
            );

        const result =
            await response.json();

        if (result.success) {

            showToast(
                result.message,
                'success'
            );

        } else {

            showToast(
                result.message,
                'danger'
            );
        }

        return result;

    } catch(error) {

        showToast(
            'Connection error.',
            'danger'
        );

        return false;
    }
}

/*
|--------------------------------------------------------------------------
| Exam Code Check
|--------------------------------------------------------------------------
*/

async function checkExamCode(data) {

    try {

        const response =
            await fetch(
                '../ajax/check-exam-code.php',
                {
                    method:'POST',
                    body:data
                }
            );

        const result =
            await response.json();

        if (result.success) {

            showToast(
                result.message,
                'success'
            );

            if (result.redirect) {

                setTimeout(() => {

                    window.location.href =
                        result.redirect;

                }, 1200);
            }

        } else {

            showToast(
                result.message,
                'danger'
            );
        }

        return result;

    } catch(error) {

        showToast(
            'Connection error.',
            'danger'
        );

        return false;
    }
}

/*
|--------------------------------------------------------------------------
| Search Filter
|--------------------------------------------------------------------------
*/

function liveSearch(
    inputSelector,
    itemSelector
) {

    const input =
        document.querySelector(
            inputSelector
        );

    if (!input) {

        return;
    }

    input.addEventListener('keyup', () => {

        const value =
            input.value.toLowerCase();

        document
        .querySelectorAll(itemSelector)
        .forEach(item => {

            const text =
                item.innerText.toLowerCase();

            item.style.display =
                text.includes(value)
                ? ''
                : 'none';
        });
    });
}

/*
|--------------------------------------------------------------------------
| Auto Close Alerts
|--------------------------------------------------------------------------
*/

document.addEventListener('DOMContentLoaded', () => {

    setTimeout(() => {

        document
        .querySelectorAll('.alert')
        .forEach(alert => {

            alert.style.transition =
                '0.4s';

            alert.style.opacity =
                '0';

            setTimeout(() => {

                alert.remove();

            }, 400);
        });

    }, 4500);
});

/*
|--------------------------------------------------------------------------
| Sidebar Toggle
|--------------------------------------------------------------------------
*/

function toggleSidebar() {

    const sidebar =
        document.querySelector('.sidebar');

    if (!sidebar) {

        return;
    }

    sidebar.classList.toggle('show');
}

/*
|--------------------------------------------------------------------------
| Dynamic Progress Bar
|--------------------------------------------------------------------------
*/

function animateProgressBars() {

    document
    .querySelectorAll('.progress-fill')
    .forEach(bar => {

        const width =
            bar.dataset.width || '0';

        setTimeout(() => {

            bar.style.width =
                width + '%';

        }, 200);
    });
}

document.addEventListener(
    'DOMContentLoaded',
    animateProgressBars
);

/*
|--------------------------------------------------------------------------
| Toast Styles
|--------------------------------------------------------------------------
*/

const toastStyle =
document.createElement('style');

toastStyle.innerHTML = `

.smi-toast{

    position:fixed;

    top:30px;
    right:30px;

    min-width:280px;

    max-width:420px;

    padding:18px 22px;

    border-radius:20px;

    color:#fff;

    font-weight:800;

    z-index:999999;

    opacity:0;

    transform:translateY(-20px);

    transition:0.3s;

    box-shadow:
        0 18px 50px rgba(15,23,42,0.18);
}

.smi-toast.show{

    opacity:1;

    transform:translateY(0);
}

.smi-toast-success{

    background:
    linear-gradient(
        135deg,
        #16a34a,
        #15803d
    );
}

.smi-toast-danger{

    background:
    linear-gradient(
        135deg,
        #dc2626,
        #991b1b
    );
}

`;

document.head.appendChild(toastStyle);