// Custom JavaScript for Association Sportive Management System

// Wait for the DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Initialize date pickers if available
    if (typeof flatpickr !== 'undefined') {
        flatpickr(".date-picker", {
            dateFormat: "d/m/Y",
            locale: "ar"
        });
    }
    
    // Auto-close alerts after 5 seconds
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
    
    // Handle member photo preview
    const photoInput = document.getElementById('photo');
    const photoPreview = document.getElementById('photoPreview');
    
    if (photoInput && photoPreview) {
        photoInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                
                reader.onload = function(e) {
                    photoPreview.src = e.target.result;
                    photoPreview.style.display = 'block';
                }
                
                reader.readAsDataURL(this.files[0]);
            }
        });
    }
    
    // Handle category change for subscription fee calculation
    const categorySelect = document.getElementById('category_id');
    const subscriptionFeeInput = document.getElementById('subscription_fee');
    const insuranceFeeInput = document.getElementById('insurance_fee');
    const totalAmountInput = document.getElementById('amount_paid');
    
    if (categorySelect && subscriptionFeeInput && insuranceFeeInput && totalAmountInput) {
        categorySelect.addEventListener('change', function() {
            const categoryId = this.value;
            
            if (categoryId) {
                // Fetch category fees via AJAX
                fetch('get_category_fees.php?id=' + categoryId)
                    .then(response => response.json())
                    .then(data => {
                        subscriptionFeeInput.value = data.subscription_fee;
                        insuranceFeeInput.value = data.insurance_fee;
                        calculateTotal();
                    })
                    .catch(error => console.error('Error fetching category fees:', error));
            } else {
                subscriptionFeeInput.value = '';
                insuranceFeeInput.value = '';
                totalAmountInput.value = '';
            }
        });
        
        // Calculate total amount
        function calculateTotal() {
            const subscriptionFee = parseFloat(subscriptionFeeInput.value) || 0;
            const insuranceFee = parseFloat(insuranceFeeInput.value) || 0;
            totalAmountInput.value = (subscriptionFee + insuranceFee).toFixed(2);
        }
        
        // Recalculate when fees change
        subscriptionFeeInput.addEventListener('input', calculateTotal);
        insuranceFeeInput.addEventListener('input', calculateTotal);
    }
    
    // Handle print buttons
    const printButtons = document.querySelectorAll('.btn-print');
    
    if (printButtons.length > 0) {
        printButtons.forEach(function(button) {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                window.print();
            });
        });
    }
    
    // Handle delete confirmations
    const deleteButtons = document.querySelectorAll('.btn-delete');
    
    if (deleteButtons.length > 0) {
        deleteButtons.forEach(function(button) {
            button.addEventListener('click', function(e) {
                if (!confirm('هل أنت متأكد من رغبتك في الحذف؟ هذا الإجراء لا يمكن التراجع عنه.')) {
                    e.preventDefault();
                }
            });
        });
    }
    
    // Handle attendance form
    const attendanceForm = document.getElementById('attendanceForm');
    
    if (attendanceForm) {
        const sessionSelect = document.getElementById('training_session_id');
        const attendanceDate = document.getElementById('session_date');
        const membersList = document.getElementById('membersList');
        
        if (sessionSelect && attendanceDate && membersList) {
            // Load members for selected session and date
            function loadMembers() {
                const sessionId = sessionSelect.value;
                const date = attendanceDate.value;
                
                if (sessionId && date) {
                    // Show loading indicator
                    membersList.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">جاري التحميل...</span></div></div>';
                    
                    // Fetch members via AJAX
                    fetch(`get_session_members.php?session_id=${sessionId}&date=${date}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.length > 0) {
                                let html = '<div class="table-responsive"><table class="table table-striped">';
                                html += '<thead><tr><th>الاسم</th><th>الفئة</th><th>الحالة</th><th>ملاحظات</th></tr></thead><tbody>';
                                
                                data.forEach(member => {
                                    html += `<tr>
                                        <td>${member.first_name} ${member.last_name}</td>
                                        <td>${member.category_name}</td>
                                        <td>
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="attendance[${member.id}]" id="present_${member.id}" value="present" ${member.status === 'present' ? 'checked' : ''}>
                                                <label class="form-check-label" for="present_${member.id}">حاضر</label>
                                            </div>
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="attendance[${member.id}]" id="absent_${member.id}" value="absent" ${member.status === 'absent' ? 'checked' : ''}>
                                                <label class="form-check-label" for="absent_${member.id}">غائب</label>
                                            </div>
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="attendance[${member.id}]" id="excused_${member.id}" value="excused" ${member.status === 'excused' ? 'checked' : ''}>
                                                <label class="form-check-label" for="excused_${member.id}">معذور</label>
                                            </div>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control form-control-sm" name="notes[${member.id}]" value="${member.notes || ''}">
                                        </td>
                                    </tr>`;
                                });
                                
                                html += '</tbody></table></div>';
                                html += '<div class="text-center mt-3"><button type="submit" class="btn btn-primary">حفظ سجل الحضور</button></div>';
                                
                                membersList.innerHTML = html;
                            } else {
                                membersList.innerHTML = '<div class="alert alert-info">لا يوجد منخرطين في هذه الحصة.</div>';
                            }
                        })
                        .catch(error => {
                            console.error('Error fetching members:', error);
                            membersList.innerHTML = '<div class="alert alert-danger">حدث خطأ أثناء تحميل المنخرطين.</div>';
                        });
                } else {
                    membersList.innerHTML = '<div class="alert alert-warning">يرجى اختيار الحصة والتاريخ.</div>';
                }
            }
            
            sessionSelect.addEventListener('change', loadMembers);
            attendanceDate.addEventListener('change', loadMembers);
        }
    }
    
    // Handle financial reports
    const reportForm = document.getElementById('reportForm');
    
    if (reportForm) {
        const reportType = document.getElementById('report_type');
        const dateRangeDiv = document.getElementById('dateRangeDiv');
        const monthDiv = document.getElementById('monthDiv');
        const yearDiv = document.getElementById('yearDiv');
        
        if (reportType && dateRangeDiv && monthDiv && yearDiv) {
            reportType.addEventListener('change', function() {
                const value = this.value;
                
                dateRangeDiv.style.display = 'none';
                monthDiv.style.display = 'none';
                yearDiv.style.display = 'none';
                
                if (value === 'custom') {
                    dateRangeDiv.style.display = 'block';
                } else if (value === 'monthly') {
                    monthDiv.style.display = 'block';
                } else if (value === 'yearly') {
                    yearDiv.style.display = 'block';
                }
            });
            
            // Trigger change event to set initial state
            reportType.dispatchEvent(new Event('change'));
        }
    }
});
