/**
 * Notifications Page JavaScript
 * 
 * Handles the notifications and assignments tables and settings
 */

$(function() {
    // Initialize notifications table
    const notificationsTable = $('#notificationsTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: 'api/notifications/list.php',
            dataSrc: function(response) {
                return response.success ? response.data.notifications : [];
            }
        },
        columns: [
            { 
                data: 'type',
                render: function(data, type, row) {
                    return getNotificationTypeBadge(data);
                }
            },
            { data: 'title' },
            { 
                data: 'message',
                render: function(data, type, row) {
                    return type === 'display' && data.length > 50 ? 
                        data.substring(0, 50) + '...' : data;
                }
            },
            { 
                data: 'target_audience',
                render: function(data, type, row) {
                    return getTargetAudienceBadge(data);
                }
            },
            { 
                data: 'priority',
                render: function(data, type, row) {
                    return getPriorityBadge(data);
                }
            },
            { 
                data: 'is_read',
                render: function(data, type, row) {
                    return data == 1 ? 
                        '<span class="badge badge-success">Read</span>' : 
                        '<span class="badge badge-warning">Unread</span>';
                }
            },
            { 
                data: 'created_at',
                render: function(data, type, row) {
                    return formatDateTime(data);
                }
            },
            { 
                data: null,
                render: function(data, type, row) {
                    return `
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-info view-notification" data-id="${row.id}">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button type="button" class="btn btn-sm btn-danger delete-notification" data-id="${row.id}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        order: [[6, 'desc']]
    });

    // Initialize assignments table
    const assignmentsTable = $('#assignmentsTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: 'api/assignments/list.php',
            data: function(d) {
                // Add filter for only active assignments by default
                d.status = $('#assignmentStatusFilter').val() || '';
            },
            dataSrc: function(response) {
                return response.success ? response.data.assignments : [];
            }
        },
        columns: [
            { 
                data: null,
                render: function(data, type, row) {
                    return `
                        <div>
                            <strong>${row.member_name}</strong>
                            <br>
                            <small class="text-muted">${row.kso_id}</small>
                        </div>
                    `;
                }
            },
            { 
                data: 'assignment_type',
                render: function(data, type, row) {
                    return getAssignmentTypeBadge(data);
                }
            },
            { 
                data: 'priority',
                render: function(data, type, row) {
                    return getPriorityBadge(data);
                }
            },
            { data: 'assigned_by_name' },
            { 
                data: 'status',
                render: function(data, type, row) {
                    return getStatusBadge(data);
                }
            },
            { 
                data: 'due_date',
                render: function(data, type, row) {
                    if (!data) return 'N/A';
                    const dueDate = new Date(data);
                    const today = new Date();
                    
                    // If due date is in the past and status is active, highlight in red
                    if (dueDate < today && row.status === 'active') {
                        return `<span class="text-danger">${formatDate(data)} (Overdue)</span>`;
                    }
                    
                    return formatDate(data);
                }
            },
            { 
                data: 'created_at',
                render: function(data, type, row) {
                    return formatDateTime(data);
                }
            },
            { 
                data: null,
                render: function(data, type, row) {
                    let buttons = `
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-info view-assignment" data-id="${row.id}">
                                <i class="fas fa-eye"></i>
                            </button>`;
                    
                    // Only show complete button for active assignments
                    if (row.status === 'active' || row.status === 'overdue') {
                        buttons += `
                            <button type="button" class="btn btn-sm btn-success complete-assignment" data-id="${row.id}">
                                <i class="fas fa-check"></i>
                            </button>
                            <button type="button" class="btn btn-sm btn-danger cancel-assignment" data-id="${row.id}">
                                <i class="fas fa-times"></i>
                            </button>`;
                    }
                    
                    buttons += `</div>`;
                    return buttons;
                }
            }
        ],
        order: [[6, 'desc']]
    });

    // Event handler for viewing notification
    $(document).on('click', '.view-notification', function() {
        const id = $(this).data('id');
        
        // Get notification details
        $.ajax({
            url: `api/notifications/get.php?id=${id}`,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const notification = response.data;
                    
                    // Show notification details in modal
                    $('#viewNotificationModal .modal-title').text(notification.title);
                    $('#notificationMessage').text(notification.message);
                    $('#notificationCreatedBy').text(notification.created_by_name || 'System');
                    $('#notificationCreatedAt').text(formatDateTime(notification.created_at));
                    $('#notificationPriority').html(getPriorityBadge(notification.priority));
                    $('#notificationType').html(getNotificationTypeBadge(notification.type));
                    
                    // Show modal
                    $('#viewNotificationModal').modal('show');
                    
                    // Mark as read
                    $.post('api/notifications/mark_read.php', {notification_id: id});
                }
            }
        });
    });

    // Event handler for deleting notification
    $(document).on('click', '.delete-notification', function() {
        const id = $(this).data('id');
        
        if (confirm('Are you sure you want to delete this notification?')) {
            $.ajax({
                url: 'api/notifications/delete.php',
                method: 'POST',
                data: {notification_id: id},
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Refresh the table
                        notificationsTable.ajax.reload();
                        
                        // Show success message
                        toastr.success('Notification deleted successfully');
                    } else {
                        toastr.error(response.message || 'Error deleting notification');
                    }
                }
            });
        }
    });

    // Event handler for viewing assignment
    $(document).on('click', '.view-assignment', function() {
        const id = $(this).data('id');
        
        // Get assignment details
        $.ajax({
            url: `api/assignments/get.php?id=${id}`,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    const assignment = response.data;
                    
                    // Show assignment details in modal
                    $('#viewAssignmentModal .modal-title').text(`Assignment for ${assignment.member_name}`);
                    $('#assignmentType').html(getAssignmentTypeBadge(assignment.assignment_type));
                    $('#assignmentPriority').html(getPriorityBadge(assignment.priority));
                    $('#assignmentStatus').html(getStatusBadge(assignment.status));
                    $('#assignmentDueDate').text(assignment.due_date ? formatDate(assignment.due_date) : 'N/A');
                    $('#assignmentCreatedAt').text(formatDateTime(assignment.created_at));
                    $('#assignmentAssignedBy').text(assignment.assigned_by_name);
                    $('#assignmentNotes').text(assignment.notes || 'No notes');
                    
                    // Show modal
                    $('#viewAssignmentModal').modal('show');
                }
            }
        });
    });

    // Event handler for completing assignment
    $(document).on('click', '.complete-assignment', function() {
        const id = $(this).data('id');
        
        // Show complete assignment modal
        $('#completeAssignmentModal').modal('show');
        $('#completeAssignmentId').val(id);
    });

    // Event handler for cancelling assignment
    $(document).on('click', '.cancel-assignment', function() {
        const id = $(this).data('id');
        
        if (confirm('Are you sure you want to cancel this assignment?')) {
            $.ajax({
                url: 'api/assignments/update_status.php',
                method: 'POST',
                data: {
                    assignment_id: id,
                    status: 'cancelled',
                    notes: 'Cancelled by user'
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Refresh the table
                        assignmentsTable.ajax.reload();
                        
                        // Show success message
                        toastr.success('Assignment cancelled successfully');
                    } else {
                        toastr.error(response.message || 'Error cancelling assignment');
                    }
                }
            });
        }
    });

    // Event handler for complete assignment form submission
    $('#completeAssignmentForm').on('submit', function(e) {
        e.preventDefault();
        
        const id = $('#completeAssignmentId').val();
        const notes = $('#completeAssignmentNotes').val();
        
        $.ajax({
            url: 'api/assignments/update_status.php',
            method: 'POST',
            data: {
                assignment_id: id,
                status: 'completed',
                notes: notes
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Close modal
                    $('#completeAssignmentModal').modal('hide');
                    
                    // Refresh the table
                    assignmentsTable.ajax.reload();
                    
                    // Show success message
                    toastr.success('Assignment completed successfully');
                    
                    // Clear form
                    $('#completeAssignmentNotes').val('');
                } else {
                    toastr.error(response.message || 'Error completing assignment');
                }
            }
        });
    });

    // Event handler for create notification form submission
    $('#createNotificationForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = $(this).serialize();
        
        $.ajax({
            url: 'api/notifications/create.php',
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Close modal
                    $('#createNotificationModal').modal('hide');
                    
                    // Refresh the table
                    notificationsTable.ajax.reload();
                    
                    // Show success message
                    toastr.success('Notification created successfully');
                    
                    // Clear form
                    $('#createNotificationForm')[0].reset();
                } else {
                    toastr.error(response.message || 'Error creating notification');
                }
            }
        });
    });

    // Event handler for create assignment form submission
    $('#createAssignmentForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = $(this).serialize();
        
        $.ajax({
            url: 'api/assignments/create.php',
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Close modal
                    $('#createAssignmentModal').modal('hide');
                    
                    // Refresh the table
                    assignmentsTable.ajax.reload();
                    
                    // Show success message
                    toastr.success('Assignment created successfully');
                    
                    // Clear form
                    $('#createAssignmentForm')[0].reset();
                } else {
                    toastr.error(response.message || 'Error creating assignment');
                }
            }
        });
    });

    // Event handler for notification settings form submission
    $('#notificationSettingsForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = $(this).serialize();
        
        $.ajax({
            url: 'api/notifications/settings.php',
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Show success message
                    toastr.success('Notification settings updated successfully');
                    
                    // Update notification system settings
                    if (window.notificationSystem) {
                        notificationSystem.toggleSound($('#soundNotifications').is(':checked'));
                        notificationSystem.toggleBrowserNotifications($('#browserNotifications').is(':checked'));
                    }
                } else {
                    toastr.error(response.message || 'Error updating notification settings');
                }
            }
        });
    });

    // Filter assignments by status
    $('#assignmentStatusFilter').on('change', function() {
        assignmentsTable.ajax.reload();
    });

    // Load notification settings
    $.ajax({
        url: 'api/notifications/settings.php',
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const settings = response.data;
                
                // Update form values
                $('#browserNotifications').prop('checked', settings.browser_notifications == 1);
                $('#soundNotifications').prop('checked', settings.sound_notifications == 1);
                $('#emailNotifications').prop('checked', settings.email_notifications == 1);
                
                // Update notification types checkboxes
                if (settings.notification_types) {
                    const types = JSON.parse(settings.notification_types);
                    $('input[name="notification_types[]"]').each(function() {
                        $(this).prop('checked', types.includes($(this).val()));
                    });
                }
            }
        }
    });

    // Helper function to format date
    function formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString();
    }

    // Helper function to format date and time
    function formatDateTime(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }

    // Helper function to get notification type badge
    function getNotificationTypeBadge(type) {
        let badgeClass = 'badge ';
        let icon = '';
        
        switch (type) {
            case 'info':
                badgeClass += 'badge-info';
                icon = 'fas fa-info-circle';
                break;
            case 'success':
                badgeClass += 'badge-success';
                icon = 'fas fa-check-circle';
                break;
            case 'warning':
                badgeClass += 'badge-warning';
                icon = 'fas fa-exclamation-triangle';
                break;
            case 'error':
                badgeClass += 'badge-danger';
                icon = 'fas fa-times-circle';
                break;
            case 'announcement':
                badgeClass += 'badge-primary';
                icon = 'fas fa-bullhorn';
                break;
            case 'event':
                badgeClass += 'badge-indigo';
                icon = 'fas fa-calendar-alt';
                break;
            case 'payment':
                badgeClass += 'badge-success';
                icon = 'fas fa-money-bill-wave';
                break;
            case 'membership':
                badgeClass += 'badge-primary';
                icon = 'fas fa-user-tag';
                break;
            default:
                badgeClass += 'badge-secondary';
                icon = 'fas fa-bell';
        }
        
        return `<span class="${badgeClass}"><i class="${icon} mr-1"></i> ${type.charAt(0).toUpperCase() + type.slice(1)}</span>`;
    }

    // Helper function to get target audience badge
    function getTargetAudienceBadge(audience) {
        let badgeClass = 'badge ';
        
        switch (audience) {
            case 'all':
                badgeClass += 'badge-primary';
                break;
            case 'admins':
                badgeClass += 'badge-info';
                break;
            case 'members':
                badgeClass += 'badge-success';
                break;
            case 'specific':
                badgeClass += 'badge-warning';
                break;
            default:
                badgeClass += 'badge-secondary';
        }
        
        return `<span class="${badgeClass}">${audience.charAt(0).toUpperCase() + audience.slice(1)}</span>`;
    }

    // Helper function to get priority badge
    function getPriorityBadge(priority) {
        let badgeClass = 'badge ';
        
        switch (priority) {
            case 'low':
                badgeClass += 'badge-secondary';
                break;
            case 'normal':
                badgeClass += 'badge-info';
                break;
            case 'high':
                badgeClass += 'badge-warning';
                break;
            case 'urgent':
                badgeClass += 'badge-danger';
                break;
            default:
                badgeClass += 'badge-secondary';
        }
        
        return `<span class="${badgeClass}">${priority.charAt(0).toUpperCase() + priority.slice(1)}</span>`;
    }

    // Helper function to get assignment type badge
    function getAssignmentTypeBadge(type) {
        let badgeClass = 'badge ';
        
        switch (type) {
            case 'review':
                badgeClass += 'badge-primary';
                break;
            case 'approval':
                badgeClass += 'badge-success';
                break;
            case 'verification':
                badgeClass += 'badge-info';
                break;
            case 'follow_up':
                badgeClass += 'badge-warning';
                break;
            default:
                badgeClass += 'badge-secondary';
        }
        
        return `<span class="${badgeClass}">${type.charAt(0).toUpperCase() + type.slice(1)}</span>`;
    }

    // Helper function to get status badge
    function getStatusBadge(status) {
        let badgeClass = 'badge ';
        
        switch (status) {
            case 'active':
                badgeClass += 'badge-primary';
                break;
            case 'completed':
                badgeClass += 'badge-success';
                break;
            case 'cancelled':
                badgeClass += 'badge-secondary';
                break;
            case 'overdue':
                badgeClass += 'badge-danger';
                break;
            default:
                badgeClass += 'badge-secondary';
        }
        
        return `<span class="${badgeClass}">${status.charAt(0).toUpperCase() + status.slice(1)}</span>`;
    }
});
