/**
 * Koperasi Management System - App JavaScript
 */

// ============================================
// Modal Functions
// ============================================
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    const overlay = document.getElementById('modalOverlay');
    if (modal && overlay) {
        overlay.classList.add('active');
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    const overlay = document.getElementById('modalOverlay');
    if (modal && overlay) {
        overlay.classList.remove('active');
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

function closeAllModals() {
    document.querySelectorAll('.modal.active').forEach(modal => {
        modal.classList.remove('active');
    });
    const overlay = document.getElementById('modalOverlay');
    if (overlay) overlay.classList.remove('active');
    document.body.style.overflow = '';
}

// Close modal on overlay click
document.addEventListener('click', function (e) {
    // Don't close modal when clicking on topbar or its children
    const topbar = document.querySelector('.topbar');
    if (topbar && topbar.contains(e.target)) {
        return;
    }
    
    if (e.target.classList.contains('modal-overlay') && e.target.classList.contains('active')) {
        closeAllModals();
    }
});

// Close modal on Escape key
document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
        closeAllModals();
    }
});

// ============================================
// Alert Auto-dismiss
// ============================================
document.addEventListener('DOMContentLoaded', function () {
    // Auto-dismiss alerts after 5 seconds
    document.querySelectorAll('.alert').forEach(alert => {
        setTimeout(() => {
            alert.style.transition = 'all 0.3s ease';
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-10px)';
            setTimeout(() => alert.remove(), 300);
        }, 5000);
    });

    // Alert close buttons
    document.querySelectorAll('.alert-close').forEach(btn => {
        btn.addEventListener('click', function () {
            const alert = this.closest('.alert');
            alert.style.transition = 'all 0.3s ease';
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-10px)';
            setTimeout(() => alert.remove(), 300);
        });
    });
});

// ============================================
// Sidebar Toggle (Mobile)
// ============================================
function toggleSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    if (sidebar) {
        sidebar.classList.toggle('open');
        if (overlay) overlay.classList.toggle('active');
    }
}

// Close sidebar when clicking overlay
document.addEventListener('click', function (e) {
    if (e.target.classList.contains('sidebar-overlay')) {
        const sidebar = document.querySelector('.sidebar');
        if (sidebar) sidebar.classList.remove('open');
        e.target.classList.remove('active');
    }
});

// ============================================
// Sidebar Collapse Toggle (Desktop)
// ============================================
function toggleSidebarCollapse() {
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');
    
    if (sidebar && mainContent) {
        sidebar.classList.toggle('collapsed');
        mainContent.classList.toggle('sidebar-collapsed');
        
        // Save state to localStorage
        const isCollapsed = sidebar.classList.contains('collapsed');
        localStorage.setItem('sidebarCollapsed', isCollapsed);
    }
}

// Restore sidebar collapse state on page load
document.addEventListener('DOMContentLoaded', function () {
    const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    if (isCollapsed) {
        toggleSidebarCollapse();
    }
});

// ============================================
// Form Validation
// ============================================
function validateForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return false;

    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');

    requiredFields.forEach(field => {
        removeFieldError(field);

        if (!field.value.trim()) {
            showFieldError(field, 'Field ini wajib diisi');
            isValid = false;
        }
    });

    return isValid;
}

function showFieldError(field, message) {
    field.style.borderColor = 'var(--danger-500)';

    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) existingError.remove();

    const error = document.createElement('span');
    error.className = 'field-error';
    error.style.cssText = 'color: var(--danger-500); font-size: 0.78rem; margin-top: 4px; display: block;';
    error.textContent = message;
    field.parentNode.appendChild(error);
}

function removeFieldError(field) {
    field.style.borderColor = '';
    const error = field.parentNode.querySelector('.field-error');
    if (error) error.remove();
}

// Remove error on input
document.addEventListener('input', function (e) {
    if (e.target.classList.contains('form-control')) {
        removeFieldError(e.target);
    }
});

// ============================================
// Format Currency Input
// ============================================
function formatCurrencyInput(input) {
    let value = input.value.replace(/\D/g, '');
    if (value) {
        value = parseInt(value).toLocaleString('id-ID');
    }
    input.value = value;
}

function parseCurrency(value) {
    return parseInt(value.replace(/\./g, '').replace(/\D/g, '')) || 0;
}

// ============================================
// Confirm Delete
// ============================================
function confirmDelete(message, url) {
    if (confirm(message || 'Apakah Anda yakin ingin menghapus data ini?')) {
        window.location.href = url;
    }
}

// ============================================
// Search Filter (Client-side)
// ============================================
function filterTable(inputId, tableId) {
    const input = document.getElementById(inputId);
    const table = document.getElementById(tableId);

    if (!input || !table) return;

    const filter = input.value.toLowerCase();
    const rows = table.querySelectorAll('tbody tr');

    rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(filter) ? '' : 'none';
    });
}

// ============================================
// Print
// ============================================
function printPage() {
    window.print();
}

// ============================================
// Number formatting helper  
// ============================================
function formatNumber(num) {
    return new Intl.NumberFormat('id-ID').format(num);
}

// ============================================
// Loan Calculator
// ============================================
function hitungAngsuran() {
    const jumlah = parseCurrency(document.getElementById('jumlah_pinjaman')?.value || '0');
    const jasa = parseFloat(document.getElementById('jasa_persen')?.value || '0');
    const lama = parseInt(document.getElementById('lama_angsuran')?.value || '0');

    if (jumlah > 0 && jasa >= 0 && lama > 0) {
        const jasaPerBulan = jumlah * (jasa / 100);
        const pokokPerBulan = Math.ceil(jumlah / lama);
        const totaljasa = jasaPerBulan * lama;
        const totalBayar = jumlah + totaljasa;
        const angsuranPerBulan = Math.ceil(totalBayar / lama);

        const elPokokRaw = document.getElementById('pokok_per_bulan_display');
        const elJasaRaw = document.getElementById('jasa_per_bulan_display');
        const elAngsuran = document.getElementById('jumlah_angsuran_display');
        const elTotal = document.getElementById('total_bayar_display');

        if (elPokokRaw) elPokokRaw.textContent = 'Rp ' + formatNumber(pokokPerBulan);
        if (elJasaRaw) elJasaRaw.textContent = 'Rp ' + formatNumber(jasaPerBulan);
        if (elAngsuran) elAngsuran.textContent = 'Rp ' + formatNumber(angsuranPerBulan);
        if (elTotal) elTotal.textContent = 'Rp ' + formatNumber(totalBayar);

        // Set hidden fields
        const hAngsuran = document.getElementById('jumlah_angsuran_val');
        const hTotal = document.getElementById('total_bayar_val');
        if (hAngsuran) hAngsuran.value = angsuranPerBulan;
        if (hTotal) hTotal.value = totalBayar;
    }
}

// ============================================
// Real-time Clock & Header Dropdown
// ============================================
document.addEventListener('DOMContentLoaded', function () {
    // 1. Real-time Clock
    const dateEl = document.getElementById('header-date');
    const clockEl = document.getElementById('header-clock');

    function updateClock() {
        const now = new Date();

        // Date format: Rabu, 25 Feb 2026
        const options = { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' };
        if (dateEl) dateEl.textContent = now.toLocaleDateString('id-ID', options);

        // Time format: 14:30:05 WIB
        const timeStr = now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) + ' WIB';
        if (clockEl) clockEl.textContent = timeStr;
    }

    if (dateEl || clockEl) {
        updateClock();
        setInterval(updateClock, 1000);
    }

    // 2. User Dropdown Toggle
    const dropdownToggle = document.getElementById('userDropdownToggle');
    const dropdownMenu = document.getElementById('userDropdownMenu');
    const notifToggle = document.getElementById('notificationToggle');
    const notifMenu = document.getElementById('notificationMenu');

    // Define closeAllDropdowns in global scope
    window.closeAllDropdowns = function() {
        if (dropdownMenu) dropdownMenu.classList.remove('show');
        if (dropdownToggle) dropdownToggle.classList.remove('active');
        if (notifMenu) notifMenu.classList.remove('show');
        if (notifToggle) notifToggle.classList.remove('active');
        // Also close search dropdown if exists
        const searchMenu = document.getElementById('searchMenu');
        const searchToggle = document.getElementById('searchToggle');
        if (searchMenu) searchMenu.classList.remove('show');
        if (searchToggle) searchToggle.classList.remove('active');
    };

    if (dropdownToggle && dropdownMenu) {
        dropdownToggle.addEventListener('click', function (e) {
            e.stopPropagation();
            const isOpen = dropdownMenu.classList.contains('show');
            closeAllDropdowns();
            if (!isOpen) {
                dropdownMenu.classList.add('show');
                dropdownToggle.classList.add('active');
            }
        });
    }

    if (notifToggle && notifMenu) {
        notifToggle.addEventListener('click', function (e) {
            e.stopPropagation();
            const isOpen = notifMenu.classList.contains('show');
            closeAllDropdowns();
            if (!isOpen) {
                notifMenu.classList.add('show');
                notifToggle.classList.add('active');
            }
        });
    }

    // Close dropdowns when clicking outside
    document.addEventListener('click', function (e) {
        if (
            (dropdownToggle && !dropdownToggle.contains(e.target) && dropdownMenu && !dropdownMenu.contains(e.target)) &&
            (notifToggle && !notifToggle.contains(e.target) && notifMenu && !notifMenu.contains(e.target))
        ) {
            closeAllDropdowns();
        }
    });
});

// ============================================
// Global Search Functionality
// ============================================
document.addEventListener('DOMContentLoaded', function () {
    const searchToggle = document.getElementById('searchToggle');
    const searchMenu = document.getElementById('searchMenu');
    const globalSearch = document.getElementById('globalSearch');
    const searchResults = document.getElementById('searchResults');
    const searchAllLink = document.getElementById('searchAllLink');
    
    // Toggle search dropdown
    if (searchToggle && searchMenu) {
        searchToggle.addEventListener('click', function (e) {
            e.stopPropagation();
            const isOpen = searchMenu.classList.contains('show');
            closeAllDropdowns();
            if (!isOpen) {
                searchMenu.classList.add('show');
                searchToggle.classList.add('active');
                setTimeout(() => {
                    if (globalSearch) globalSearch.focus();
                }, 100);
            }
        });
    }
    
    // Close search when clicking outside
    document.addEventListener('click', function (e) {
        if (searchToggle && searchMenu) {
            if (!searchToggle.contains(e.target) && !searchMenu.contains(e.target)) {
                searchMenu.classList.remove('show');
                searchToggle.classList.remove('active');
            }
        }
    });
    
    // Handle search input
    if (globalSearch && searchResults) {
        let searchTimeout;
        
        globalSearch.addEventListener('input', function () {
            const query = this.value.trim();
            
            // Update the "See all results" link with search query
            if (searchAllLink) {
                searchAllLink.href = '<?= APP_URL ?>/anggota.php?search=' + encodeURIComponent(query);
            }
            
            // Clear previous timeout
            clearTimeout(searchTimeout);
            
            if (query.length < 2) {
                searchResults.innerHTML = `
                    <div class="search-hint">
                        <i class="fas fa-keyboard"></i>
                        <span>Ketik untuk mencari...</span>
                    </div>
                `;
                return;
            }
            
            // Show loading state
            searchResults.innerHTML = `
                <div class="search-loading">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>Mencari...</span>
                </div>
            `;
            
            // Debounce search request
            searchTimeout = setTimeout(() => {
                performSearch(query);
            }, 300);
        });
        
        // Handle Enter key
        globalSearch.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                const query = this.value.trim();
                if (query.length >= 2 && searchAllLink) {
                    window.location.href = '<?= APP_URL ?>/anggota.php?search=' + encodeURIComponent(query);
                }
            }
        });
    }
    
    // Search function
    function performSearch(query) {
        // Fetch search results via AJAX
        fetch('<?= APP_URL ?>/search.php?q=' + encodeURIComponent(query))
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (Array.isArray(data)) {
                    displaySearchResults(data, query);
                } else {
                    throw new Error('Invalid response format');
                }
            })
            .catch(error => {
                console.error('Search error:', error);
                searchResults.innerHTML = `
                    <div class="search-error">
                        <i class="fas fa-exclamation-triangle"></i>
                        <span>Terjadi kesalahan saat mencari</span>
                    </div>
                `;
            });
    }
    
    // Display search results
    function displaySearchResults(data, query) {
        if (!searchResults) return;
        
        if (data.length === 0) {
            searchResults.innerHTML = `
                <div class="search-empty">
                    <i class="fas fa-search"></i>
                    <span>Tidak ada hasil untuk "${escapeHtml(query)}"</span>
                </div>
            `;
            return;
        }
        
        let html = '';
        data.forEach(item => {
            html += `
                <a href="${item.url}" class="search-result-item">
                    <div class="search-result-icon">
                        <i class="fas fa-${item.icon}"></i>
                    </div>
                    <div class="search-result-content">
                        <div class="search-result-title">${escapeHtml(item.title)}</div>
                        <div class="search-result-subtitle">${escapeHtml(item.subtitle || '')}</div>
                    </div>
                    <i class="fas fa-chevron-right search-result-arrow"></i>
                </a>
            `;
        });
        
        searchResults.innerHTML = html;
    }
    
    // Escape HTML to prevent XSS
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
});
