/**
 * assets/js/dashboard.js
 * Vanilla JS for the digital register.
 * Handles modals, AJAX, search, downloads, and notifications.
 * All endpoints now point to dedicated backend files.
 */

document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    // DOM refs
    const tableBody = document.getElementById('tableBody');
    const searchInput = document.getElementById('searchInput');
    const addBtn = document.getElementById('addMemberBtn');
    const modalOverlay = document.getElementById('memberModal');
    const modalClose = document.getElementById('modalClose');
    const modalCancel = document.getElementById('modalCancel');
    const modalTitle = document.getElementById('modalTitle');
    const memberForm = document.getElementById('memberForm');
    const editId = document.getElementById('editId');
    const serialInput = document.getElementById('serialNumber');
    const nameInput = document.getElementById('fullName');
    const genderSelect = document.getElementById('gender');
    const phoneInput = document.getElementById('phoneNumber');
    const kindredInput = document.getElementById('kindred');
    const saveBtn = document.getElementById('modalSave');
    const saveText = document.getElementById('saveText');
    const saveSpinner = document.getElementById('saveSpinner');

    // View modal
    const viewModal = document.getElementById('viewModal');
    const viewClose = document.getElementById('viewClose');
    const viewDetails = document.getElementById('viewDetails');

    // Delete modal
    const deleteModal = document.getElementById('deleteModal');
    const deleteClose = document.getElementById('deleteClose');
    const deleteCancel = document.getElementById('deleteCancel');
    const deleteConfirm = document.getElementById('deleteConfirm');
    const deleteId = document.getElementById('deleteId');
    const deleteSpinner = document.getElementById('deleteSpinner');

    // Toast
    const toast = document.getElementById('toast');
    const toastMsg = document.getElementById('toastMessage');
    const toastClose = document.getElementById('toastClose');

    // Download dropdown
    const downloadBtn = document.getElementById('downloadBtn');
    const downloadMenu = document.getElementById('downloadMenu');

    // ------------------------------------------------------------------
    // Utility functions
    // ------------------------------------------------------------------

    function showToast(message, type = 'success') {
        toastMsg.textContent = message;
        toast.className = 'toast show ' + type;
        clearTimeout(toast._timeout);
        toast._timeout = setTimeout(() => {
            toast.classList.remove('show');
        }, 4000);
    }

    function closeToast() {
        toast.classList.remove('show');
        clearTimeout(toast._timeout);
    }
    toastClose.addEventListener('click', closeToast);

    // Modal helpers
    function openModal(modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    function closeModal(modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }

    // Reset member form
    function resetMemberForm() {
        memberForm.reset();
        editId.value = '0';
        modalTitle.textContent = 'Add New Member';
        saveText.textContent = 'Save';
        saveSpinner.style.display = 'none';
        saveBtn.disabled = false;
        document.querySelectorAll('.form-group .error-msg').forEach(el => el.remove());
    }

    // Fetch and reload table (update stats too)
    function refreshTable() {
        fetch(window.location.href, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(res => res.text())
            .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const newBody = doc.querySelector('#tableBody');
                if (newBody) tableBody.innerHTML = newBody.innerHTML;
                const total = doc.querySelector('#totalMembers');
                const male = doc.querySelector('#maleMembers');
                const female = doc.querySelector('#femaleMembers');
                if (total) document.getElementById('totalMembers').textContent = total.textContent;
                if (male) document.getElementById('maleMembers').textContent = male.textContent;
                if (female) document.getElementById('femaleMembers').textContent = female.textContent;
                bindActionButtons();
                // Re-apply search filter if any
                if (searchInput.value.trim() !== '') {
                    applySearchFilter(searchInput.value.trim());
                }
            })
            .catch(() => showToast('Failed to refresh data.', 'error'));
    }

    // ------------------------------------------------------------------
    // Bind action buttons (View, Edit, Delete)
    // ------------------------------------------------------------------

    function bindActionButtons() {
        // View
        document.querySelectorAll('.view-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const id = this.dataset.id;
                fetch('get-member.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'id=' + id
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        const m = data.data;
                        viewDetails.innerHTML = `
                            <div class="detail-item"><span class="detail-label">Membership ID</span><span class="detail-value">${escapeHtml(m.membership_id)}</span></div>
                            <div class="detail-item"><span class="detail-label">Full Name</span><span class="detail-value">${escapeHtml(m.full_name)}</span></div>
                            <div class="detail-item"><span class="detail-label">Gender</span><span class="detail-value">${escapeHtml(m.gender)}</span></div>
                            <div class="detail-item"><span class="detail-label">Phone</span><span class="detail-value">${escapeHtml(m.phone)}</span></div>
                            <div class="detail-item"><span class="detail-label">Email</span><span class="detail-value">${escapeHtml(m.email || '—')}</span></div>
                            <div class="detail-item"><span class="detail-label">Kindred</span><span class="detail-value">${escapeHtml(m.kindred || '—')}</span></div>
                            <div class="detail-item"><span class="detail-label">Date Joined</span><span class="detail-value">${escapeHtml(m.date_joined)}</span></div>
                            <div class="detail-item"><span class="detail-label">Status</span><span class="detail-value">${escapeHtml(m.status || 'Active')}</span></div>
                            <div class="detail-item"><span class="detail-label">Created At</span><span class="detail-value">${escapeHtml(m.created_at)}</span></div>
                        `;
                        openModal(viewModal);
                    } else {
                        showToast(data.message, 'error');
                    }
                })
                .catch(() => showToast('Error loading member details.', 'error'));
            });
        });

        // Edit
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const id = this.dataset.id;
                fetch('get-member.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'id=' + id
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        const m = data.data;
                        editId.value = m.id;
                        serialInput.value = m.membership_id;
                        nameInput.value = m.full_name;
                        genderSelect.value = m.gender;
                        phoneInput.value = m.phone;
                        kindredInput.value = m.kindred || '';
                        modalTitle.textContent = 'Edit Member';
                        saveText.textContent = 'Update';
                        saveSpinner.style.display = 'none';
                        saveBtn.disabled = false;
                        openModal(modalOverlay);
                    } else {
                        showToast(data.message, 'error');
                    }
                })
                .catch(() => showToast('Error loading member for edit.', 'error'));
            });
        });

        // Delete
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const id = this.dataset.id;
                deleteId.value = id;
                openModal(deleteModal);
            });
        });
    }

    // Simple HTML escaping
    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // ------------------------------------------------------------------
    // Add Member – open modal (empty)
    // ------------------------------------------------------------------

    addBtn.addEventListener('click', function() {
        resetMemberForm();
        openModal(modalOverlay);
    });

    // Close modals
    modalClose.addEventListener('click', () => closeModal(modalOverlay));
    modalCancel.addEventListener('click', () => closeModal(modalOverlay));
    viewClose.addEventListener('click', () => closeModal(viewModal));
    deleteClose.addEventListener('click', () => closeModal(deleteModal));
    deleteCancel.addEventListener('click', () => closeModal(deleteModal));

    // Close modals on backdrop click
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', function(e) {
            if (e.target === this) closeModal(this);
        });
    });

    // ------------------------------------------------------------------
    // Submit member form (add / edit)
    // ------------------------------------------------------------------

    memberForm.addEventListener('submit', function(e) {
        e.preventDefault();

        // Validate
        const serial = serialInput.value.trim();
        const name = nameInput.value.trim();
        const gender = genderSelect.value;
        const phone = phoneInput.value.trim();
        if (!serial || !name || !gender || !phone) {
            showToast('Please fill in all required fields.', 'error');
            return;
        }

        // Disable save button and show spinner
        saveBtn.disabled = true;
        saveText.textContent = 'Saving...';
        saveSpinner.style.display = 'inline-block';

        const isEdit = editId.value > 0;
        const formData = new FormData(this);
        const endpoint = isEdit ? 'update-member.php' : 'save-member.php';

        fetch(endpoint, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                closeModal(modalOverlay);
                refreshTable();
            } else {
                showToast(data.message, 'error');
            }
        })
        .catch(() => showToast('Network error. Please try again.', 'error'))
        .finally(() => {
            saveBtn.disabled = false;
            saveText.textContent = isEdit ? 'Update' : 'Save';
            saveSpinner.style.display = 'none';
        });
    });

    // ------------------------------------------------------------------
    // Delete confirmation
    // ------------------------------------------------------------------

    deleteConfirm.addEventListener('click', function() {
        const id = deleteId.value;
        if (!id) return;

        deleteConfirm.disabled = true;
        deleteSpinner.style.display = 'inline-block';
        deleteConfirm.querySelector('span').textContent = 'Deleting...';

        fetch('delete-member.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'id=' + id
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                closeModal(deleteModal);
                refreshTable();
            } else {
                showToast(data.message, 'error');
            }
        })
        .catch(() => showToast('Error deleting member.', 'error'))
        .finally(() => {
            deleteConfirm.disabled = false;
            deleteSpinner.style.display = 'none';
            deleteConfirm.querySelector('span').textContent = 'Delete';
        });
    });

    // ------------------------------------------------------------------
    // Search – server-side with debounce
    // ------------------------------------------------------------------

    let searchTimeout = null;

    function applySearchFilter(term) {
        const query = term.trim();
        fetch('search-member.php?q=' + encodeURIComponent(query))
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const results = data.data;
                    if (results.length === 0) {
                        tableBody.innerHTML = `<tr><td colspan="7" class="empty-row">No matching members found.</td></tr>`;
                    } else {
                        let html = '';
                        results.forEach(m => {
                            html += `
                                <tr data-id="${m.id}">
                                    <td>${escapeHtml(m.membership_id)}</td>
                                    <td>${escapeHtml(m.full_name)}</td>
                                    <td>${escapeHtml(m.gender)}</td>
                                    <td>${escapeHtml(m.phone)}</td>
                                    <td>${escapeHtml(m.kindred || '—')}</td>
                                    <td>${escapeHtml(m.date_joined ? new Date(m.date_joined).toISOString().slice(0,10) : '')}</td>
                                    <td class="actions-cell">
                                        <button class="action-btn view-btn" data-id="${m.id}" title="View"><i class="fas fa-eye"></i></button>
                                        <button class="action-btn edit-btn" data-id="${m.id}" title="Edit"><i class="fas fa-pen"></i></button>
                                        <button class="action-btn delete-btn" data-id="${m.id}" title="Delete"><i class="fas fa-trash"></i></button>
                                    </td>
                                </tr>
                            `;
                        });
                        tableBody.innerHTML = html;
                        bindActionButtons();
                    }
                } else {
                    showToast('Search failed: ' + data.message, 'error');
                }
            })
            .catch(() => showToast('Search error.', 'error'));
    }

    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const term = this.value;
        searchTimeout = setTimeout(() => {
            applySearchFilter(term);
        }, 300);
    });

    // ------------------------------------------------------------------
    // Download dropdown toggle
    // ------------------------------------------------------------------

    downloadBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        downloadMenu.classList.toggle('show');
    });

    document.addEventListener('click', function(e) {
        if (!e.target.closest('.dropdown')) {
            downloadMenu.classList.remove('show');
        }
    });

    // ------------------------------------------------------------------
    // Initial binding
    // ------------------------------------------------------------------

    bindActionButtons();

    // If search input has a value on load (e.g., from back), apply it
    if (searchInput.value.trim() !== '') {
        applySearchFilter(searchInput.value.trim());
    }
});