<?php
/**
 * Notifications Page
 * 
 * Displays and manages notifications, member assignments, and notification settings
 */

// Initialize the session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check authentication
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Set page title
$page_title = 'Notifications & Assignments';
$active_menu = 'notifications';

// Include header
require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Notifications Management</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Notifications</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Info boxes -->
            <div class="row">
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box">
                        <span class="info-box-icon bg-info elevation-1"><i class="fas fa-bell"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Notifications</span>
                            <span class="info-box-number" id="totalNotifications">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-success elevation-1"><i class="fas fa-check-circle"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Read</span>
                            <span class="info-box-number" id="readNotifications">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-envelope"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Unread</span>
                            <span class="info-box-number" id="unreadNotifications">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-exclamation-triangle"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Urgent</span>
                            <span class="info-box-number" id="urgentNotifications">0</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Notifications Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Notifications</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#createNotificationModal">
                                    <i class="fas fa-plus"></i> Create Notification
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="notificationsTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>Title</th>
                                        <th>Message</th>
                                        <th>Target Audience</th>
                                        <th>Priority</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Member Assignments -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Member Assignments</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#createAssignmentModal">
                                    <i class="fas fa-plus"></i> Create Assignment
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="assignmentsTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Member</th>
                                        <th>Type</th>
                                        <th>Priority</th>
                                        <th>Assigned By</th>
                                        <th>Status</th>
                                        <th>Due Date</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Notification Settings -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Notification Settings</h3>
                        </div>
                        <div class="card-body">
                            <form id="notificationSettingsForm">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="browserNotifications" name="browser_notifications" checked>
                                                <label class="custom-control-label" for="browserNotifications">Browser Notifications</label>
                                            </div>
                                            <small class="form-text text-muted">Show desktop notifications when new notifications arrive</small>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="soundNotifications" name="sound_notifications" checked>
                                                <label class="custom-control-label" for="soundNotifications">Sound Notifications</label>
                                            </div>
                                            <small class="form-text text-muted">Play a sound when new notifications arrive</small>
                                        </div>
                                        <div class="form-group">
                                            <div class="custom-control custom-switch">
                                                <input type="checkbox" class="custom-control-input" id="emailNotifications" name="email_notifications" checked>
                                                <label class="custom-control-label" for="emailNotifications">Email Notifications</label>
                                            </div>
                                            <small class="form-text text-muted">Send an email for important notifications</small>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Notification Types</label>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="notifyInfo" name="notification_types[]" value="info" checked>
                                                <label class="custom-control-label" for="notifyInfo">Information</label>
                                            </div>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="notifySuccess" name="notification_types[]" value="success" checked>
                                                <label class="custom-control-label" for="notifySuccess">Success</label>
                                            </div>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="notifyWarning" name="notification_types[]" value="warning" checked>
                                                <label class="custom-control-label" for="notifyWarning">Warnings</label>
                                            </div>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="notifyError" name="notification_types[]" value="error" checked>
                                                <label class="custom-control-label" for="notifyError">Errors</label>
                                            </div>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="notifyAnnouncement" name="notification_types[]" value="announcement" checked>
                                                <label class="custom-control-label" for="notifyAnnouncement">Announcements</label>
                                            </div>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="notifyEvent" name="notification_types[]" value="event" checked>
                                                <label class="custom-control-label" for="notifyEvent">Events</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary">Save Settings</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Create Notification Modal -->
<div class="modal fade" id="createNotificationModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Create New Notification</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="createNotificationForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Notification Type *</label>
                                <select class="form-control" name="type" required>
                                    <option value="">Select Type</option>
                                    <option value="info">Info</option>
                                    <option value="success">Success</option>
                                    <option value="warning">Warning</option>
                                    <option value="error">Error</option>
                                    <option value="announcement">Announcement</option>
                                    <option value="event">Event</option>
                                    <option value="payment">Payment</option>
                                    <option value="membership">Membership</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Priority *</label>
                                <select class="form-control" name="priority" required>
                                    <option value="">Select Priority</option>
                                    <option value="low">Low</option>
                                    <option value="normal">Normal</option>
                                    <option value="high">High</option>
                                    <option value="urgent">Urgent</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Title *</label>
                        <input type="text" class="form-control" name="title" required>
                    </div>
                    <div class="form-group">
                        <label>Message *</label>
                        <textarea class="form-control" name="message" rows="4" required></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Target Audience *</label>
                                <select class="form-control" name="target_audience" required>
                                    <option value="">Select Audience</option>
                                    <option value="all">All Users</option>
                                    <option value="members">Members Only</option>
                                    <option value="admins">Admins Only</option>
                                    <option value="specific">Specific User</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Specific User (if applicable)</label>
                                <select class="form-control" name="target_user_id">
                                    <option value="">Select User</option>
                                    <!-- Options will be populated via AJAX -->
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Expiry Date</label>
                        <input type="datetime-local" class="form-control" name="expires_at">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Create Notification</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Load notification statistics
    loadNotificationStats();
    loadUsers();
    
    // Initialize DataTable
    const table = $('#notificationsTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/fetch_notifications.php",
            "dataSrc": function(json) {
                return json.success ? json.data : [];
            }
        },
        "columns": [
            { "data": "type", "render": function(data) {
                const badges = {
                    'info': 'info',
                    'success': 'success',
                    'warning': 'warning',
                    'error': 'danger',
                    'announcement': 'primary',
                    'event': 'secondary',
                    'payment': 'success',
                    'membership': 'info'
                };
                return `<span class="badge badge-${badges[data] || 'secondary'}">${data}</span>`;
            }},
            { "data": "title" },
            { "data": "message", "render": function(data) {
                return data.length > 50 ? data.substring(0, 50) + '...' : data;
            }},
            { "data": "target_audience" },
            { "data": "priority", "render": function(data) {
                const badges = {
                    'low': 'secondary',
                    'normal': 'info',
                    'high': 'warning',
                    'urgent': 'danger'
                };
                return `<span class="badge badge-${badges[data] || 'secondary'}">${data}</span>`;
            }},
            { "data": "is_read", "render": function(data) {
                return data == 1 ? '<span class="badge badge-success">Read</span>' : '<span class="badge badge-warning">Unread</span>';
            }},
            { "data": "created_at", "render": function(data) {
                return new Date(data).toLocaleDateString();
            }},
            { "data": null, "render": function(data) {
                return `
                    <button class="btn btn-sm btn-info" onclick="viewNotification(${data.id})">View</button>
                    <button class="btn btn-sm btn-warning" onclick="editNotification(${data.id})">Edit</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteNotification(${data.id})">Delete</button>
                `;
            }}
        ]
    });

    // Create notification form submission
    $('#createNotificationForm').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        $.ajax({
            url: 'api/create_notification.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#createNotificationModal').modal('hide');
                    table.ajax.reload();
                    loadNotificationStats();
                    toastr.success('Notification created successfully');
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error creating notification');
            }
        });
    });

    // Show/hide specific user field based on target audience
    $('select[name="target_audience"]').on('change', function() {
        const specificUserField = $('select[name="target_user_id"]').closest('.form-group');
        if ($(this).val() === 'specific') {
            specificUserField.show();
        } else {
            specificUserField.hide();
            $('select[name="target_user_id"]').val('');
        }
    });
});

function loadNotificationStats() {
    $.get('api/fetch_notification_stats.php', function(data) {
        if (data.success) {
            $('#totalNotifications').text(data.data.total);
            $('#readNotifications').text(data.data.read);
            $('#unreadNotifications').text(data.data.unread);
            $('#urgentNotifications').text(data.data.urgent);
        }
    });
}

function loadUsers() {
    $.get('api/fetch_all_users.php', function(data) {
        if (data.success) {
            const select = $('select[name="target_user_id"]');
            select.empty().append('<option value="">Select User</option>');
            data.data.forEach(function(user) {
                select.append(`<option value="${user.id}">${user.name} (${user.type})</option>`);
            });
        }
    });
}

function viewNotification(id) {
    window.location.href = `notification-details.php?id=${id}`;
}

function editNotification(id) {
    window.location.href = `edit-notification.php?id=${id}`;
}

function deleteNotification(id) {
    if (confirm('Are you sure you want to delete this notification?')) {
        $.post('api/delete_notification.php', {id: id}, function(response) {
            if (response.success) {
                $('#notificationsTable').DataTable().ajax.reload();
                loadNotificationStats();
                toastr.success('Notification deleted successfully');
            } else {
                toastr.error(response.message);
            }
        });
    }
}
</script>

<?php require_once 'templates/footer.php'; ?>
