<?php
session_start();
require_once 'php/adminconfig.php';
// Enhanced login and role check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: signin-admin.php');
    exit();
}
// Simple logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: signin-admin.php');
    exit();
}

// Fetch all general notifications from the database
$general_query = "SELECT * FROM general_notifications ORDER BY notification_time DESC";
$general_stmt = $conn->prepare($general_query);
$general_stmt->execute();
$general_notifications = $general_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all user-specific notifications from the database
$user_query = "SELECT n.*, u.username, u.email FROM notifications n 
               LEFT JOIN users u ON n.user_id = u.id 
               ORDER BY n.created_at DESC";
$user_stmt = $conn->prepare($user_query);
$user_stmt->execute();
$user_notifications = $user_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all users for dropdown selection
$users_query = "SELECT id, username, email FROM users ORDER BY username";
$users_stmt = $conn->prepare($users_query);
$users_stmt->execute();
$users = $users_stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle general notification deletion
if (isset($_POST['delete_general_notification']) && isset($_POST['notification_id'])) {
    $notification_id = intval($_POST['notification_id']);
    
    try {
        $delete_query = "DELETE FROM general_notifications WHERE id = :notification_id";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bindParam(':notification_id', $notification_id, PDO::PARAM_INT);
        $delete_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "General notification deleted successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error deleting notification: " . $e->getMessage();
    }
}

// Handle user notification deletion
if (isset($_POST['delete_user_notification']) && isset($_POST['notification_id'])) {
    $notification_id = intval($_POST['notification_id']);
    
    try {
        $delete_query = "DELETE FROM notifications WHERE id = :notification_id";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bindParam(':notification_id', $notification_id, PDO::PARAM_INT);
        $delete_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "User notification deleted successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error deleting notification: " . $e->getMessage();
    }
}

// Handle general notification data update
if (isset($_POST['update_general_notification']) && isset($_POST['notification_id'])) {
    $notification_id = intval($_POST['notification_id']);
    $notification_title = $_POST['notification_title'];
    $notification_text = $_POST['notification_text'];
    $is_read = isset($_POST['is_read']) ? 1 : 0;
    $user_id = !empty($_POST['user_id']) ? intval($_POST['user_id']) : null;
    
    try {
        $update_query = "UPDATE general_notifications SET 
                        notification_title = :notification_title,
                        notification_text = :notification_text,
                        is_read = :is_read,
                        user_id = :user_id,
                        updated_at = CURRENT_TIMESTAMP
                        WHERE id = :notification_id";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bindParam(':notification_id', $notification_id, PDO::PARAM_INT);
        $update_stmt->bindParam(':notification_title', $notification_title);
        $update_stmt->bindParam(':notification_text', $notification_text);
        $update_stmt->bindParam(':is_read', $is_read, PDO::PARAM_INT);
        $update_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $update_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "General notification updated successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error updating notification: " . $e->getMessage();
    }
}

// Handle user notification data update
if (isset($_POST['update_user_notification']) && isset($_POST['notification_id'])) {
    $notification_id = intval($_POST['notification_id']);
    $title = $_POST['title'];
    $message = $_POST['message'];
    $type = $_POST['type'];
    $is_read = isset($_POST['is_read']) ? 1 : 0;
    $user_id = intval($_POST['user_id']);
    
    try {
        $update_query = "UPDATE notifications SET 
                        title = :title,
                        message = :message,
                        type = :type,
                        is_read = :is_read,
                        user_id = :user_id
                        WHERE id = :notification_id";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bindParam(':notification_id', $notification_id, PDO::PARAM_INT);
        $update_stmt->bindParam(':title', $title);
        $update_stmt->bindParam(':message', $message);
        $update_stmt->bindParam(':type', $type);
        $update_stmt->bindParam(':is_read', $is_read, PDO::PARAM_INT);
        $update_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $update_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "User notification updated successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error updating notification: " . $e->getMessage();
    }
}

// Handle new general notification creation
if (isset($_POST['create_general_notification'])) {
    // Required fields validation
    if (empty($_POST['notification_title']) || empty($_POST['notification_text'])) {
        $_SESSION['error_message'] = "Title and message are required for general notifications.";
    } else {
        $notification_title = $_POST['notification_title'];
        $notification_text = $_POST['notification_text'];
        $is_read = isset($_POST['is_read']) ? 1 : 0;
        $user_id = !empty($_POST['user_id']) ? intval($_POST['user_id']) : null;
        
        try {
            $insert_query = "INSERT INTO general_notifications (notification_title, notification_text, is_read, user_id) 
                           VALUES (:notification_title, :notification_text, :is_read, :user_id)";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bindParam(':notification_title', $notification_title);
            $insert_stmt->bindParam(':notification_text', $notification_text);
            $insert_stmt->bindParam(':is_read', $is_read, PDO::PARAM_INT);
            $insert_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $insert_stmt->execute();
            
            $_SESSION['success_message'] = "New general notification created successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error creating notification: " . $e->getMessage();
        }
    }
}

// Handle new user notification creation
if (isset($_POST['create_user_notification'])) {
    // Required fields validation
    if (empty($_POST['title']) || empty($_POST['message']) || empty($_POST['type']) || empty($_POST['user_id'])) {
        $_SESSION['error_message'] = "All fields are required for user notifications.";
    } else {
        $title = $_POST['title'];
        $message = $_POST['message'];
        $type = $_POST['type'];
        $user_id = intval($_POST['user_id']);
        $is_read = isset($_POST['is_read']) ? 1 : 0;
        
        try {
            $insert_query = "INSERT INTO notifications (user_id, title, message, type, is_read) 
                           VALUES (:user_id, :title, :message, :type, :is_read)";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $insert_stmt->bindParam(':title', $title);
            $insert_stmt->bindParam(':message', $message);
            $insert_stmt->bindParam(':type', $type);
            $insert_stmt->bindParam(':is_read', $is_read, PDO::PARAM_INT);
            $insert_stmt->execute();
            
            $_SESSION['success_message'] = "New user notification created successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error creating notification: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9, user-scalable=no" />
    <title>Notification Management - TradeWave plc</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="css/admin.css">
    <style>
        .notification-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        
        .tab-btn {
            padding: 10px 20px;
            background: #f5f5f5;
            border: none;
            border-radius: 5px 5px 0 0;
            cursor: pointer;
            font-weight: 600;
            margin-right: 5px;
            transition: all 0.3s ease;
        }
        
        .tab-btn.active {
            background: #007bff;
            color: white;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .notification-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 5px;
        }
        
        .badge-unread {
            background-color: #dc3545;
            color: white;
        }
        
        .badge-read {
            background-color: #28a745;
            color: white;
        }
        
        .badge-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .badge-warning {
            background-color: #ffc107;
            color: #212529;
        }
        
        .badge-success {
            background-color: #28a745;
            color: white;
        }
        
        .admin-card {
            position: relative;
        }
        
        .notification-icon {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 16px;
        }
        
        .notification-time {
            font-size: 12px;
            color: #777;
            margin-top: 5px;
        }
        
        .notification-preview {
            margin-top: 10px;
            font-size: 14px;
            color: #555;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
        
        .user-avatar {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: #007bff;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            margin-right: 5px;
        }
        
        .type-selector {
            display: flex;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .type-option {
            padding: 8px 15px;
            margin-right: 10px;
            margin-bottom: 10px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        
        .type-option:hover {
            opacity: 0.9;
        }
        
        .type-option.active {
            font-weight: bold;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .type-info {
            background-color: #cce5ff;
            border: 1px solid #b8daff;
            color: #004085;
        }
        
        .type-success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        
        .type-warning {
            background-color: #fff3cd;
            border: 1px solid #ffeeba;
            color: #856404;
        }
        
        .type-danger {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
    </style>
</head>
<body>

    <?php include "required/admin-nav.php" ?>

    <div class="pc">
    <div class="containeer">
        <div class="page-header">
            <h2 class="page-title">Manage Notifications</h2>
            <div>
                <button class="btn btn-success" id="addGeneralBtn">
                    <i class="fas fa-bullhorn"></i> New General Notification
                </button>
                <button class="btn btn-primary" id="addUserBtn">
                    <i class="fas fa-envelope"></i> New User Message
                </button>
            </div>
        </div>
        
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success">
                <span class="close-alert">&times;</span>
                <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger">
                <span class="close-alert">&times;</span>
                <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            </div>
        <?php endif; ?>
        
        <div class="notification-tabs">
            <button class="tab-btn active" data-tab="general">General Notifications</button>
            <button class="tab-btn" data-tab="user">User Messages</button>
        </div>
        
        <!-- General Notifications Tab -->
        <div class="tab-content active" id="general-tab">
            <div class="admin-grid">
                <?php if (empty($general_notifications)): ?>
                    <p class="no-data">No general notifications found.</p>
                <?php else: ?>
                    <?php foreach ($general_notifications as $notification): ?>
                        <div class="admin-card" data-id="<?php echo $notification['id']; ?>" data-type="general">
                            <div class="notification-icon">
                                <i class="fas fa-bell"></i>
                            </div>
                            <div class="admin-name">
                                <?php echo htmlspecialchars($notification['notification_title']); ?>
                                <?php if ($notification['is_read']): ?>
                                    <span class="notification-badge badge-read">Read</span>
                                <?php else: ?>
                                    <span class="notification-badge badge-unread">Unread</span>
                                <?php endif; ?>
                            </div>
                            <div class="notification-preview">
                                <?php echo htmlspecialchars(substr($notification['notification_text'], 0, 100) . '...'); ?>
                            </div>
                            <div class="notification-time">
                                <i class="fas fa-clock"></i> 
                                <?php echo date('M d, Y H:i', strtotime($notification['notification_time'])); ?>
                            </div>
                            <?php if ($notification['user_id']): ?>
                                <div class="user-info">
                                    <div class="user-avatar">
                                        <i class="fas fa-user"></i>
                                    </div>
                                    <span>For specific user</span>
                                </div>
                            <?php else: ?>
                                <div class="user-info">
                                    <div class="user-avatar">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <span>All users</span>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- User Messages Tab -->
        <div class="tab-content" id="user-tab">
            <div class="admin-grid">
                <?php if (empty($user_notifications)): ?>
                    <p class="no-data">No user messages found.</p>
                <?php else: ?>
                    <?php foreach ($user_notifications as $notification): ?>
                        <div class="admin-card" data-id="<?php echo $notification['id']; ?>" data-type="user">
                            <div class="notification-icon">
                                <?php if ($notification['type'] === 'info'): ?>
                                    <i class="fas fa-info-circle" style="color: #17a2b8;"></i>
                                <?php elseif ($notification['type'] === 'success'): ?>
                                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                                <?php elseif ($notification['type'] === 'warning'): ?>
                                    <i class="fas fa-exclamation-triangle" style="color: #ffc107;"></i>
                                <?php elseif ($notification['type'] === 'danger'): ?>
                                    <i class="fas fa-times-circle" style="color: #dc3545;"></i>
                                <?php endif; ?>
                            </div>
                            <div class="admin-name">
                                <?php echo htmlspecialchars($notification['title']); ?>
                                <span class="notification-badge badge-<?php echo htmlspecialchars($notification['type']); ?>">
                                    <?php echo ucfirst(htmlspecialchars($notification['type'])); ?>
                                </span>
                                <?php if ($notification['is_read']): ?>
                                    <span class="notification-badge badge-read">Read</span>
                                <?php else: ?>
                                    <span class="notification-badge badge-unread">Unread</span>
                                <?php endif; ?>
                            </div>
                            <div class="notification-preview">
                                <?php echo htmlspecialchars(substr($notification['message'], 0, 100) . '...'); ?>
                            </div>
                            <div class="notification-time">
                                <i class="fas fa-clock"></i> 
                                <?php echo date('M d, Y H:i', strtotime($notification['created_at'])); ?>
                            </div>
                            <div class="user-info">
                                <div class="user-avatar">
                                    <?php echo strtoupper(substr($notification['username'] ?? 'U', 0, 1)); ?>
                                </div>
                                <span><?php echo htmlspecialchars($notification['username'] ?? 'Unknown User'); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- General Notification Details Sections -->
        <?php foreach ($general_notifications as $notification): ?>
            <div class="admin-details" id="general-details-<?php echo $notification['id']; ?>">
                <h3>Edit General Notification</h3>
                
                <button class="btn btn-danger delete-btn" data-id="<?php echo $notification['id']; ?>" data-type="general">Delete This Notification</button>
                
                <form action="" method="POST" class="edit-form">
                    <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                    
                    <div class="form-group">
                        <label for="notification_title-<?php echo $notification['id']; ?>">Notification Title</label>
                        <input type="text" name="notification_title" id="notification_title-<?php echo $notification['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($notification['notification_title']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="notification_text-<?php echo $notification['id']; ?>">Notification Text</label>
                        <textarea name="notification_text" id="notification_text-<?php echo $notification['id']; ?>" class="form-control" rows="5" required><?php echo htmlspecialchars($notification['notification_text']); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="is_read-<?php echo $notification['id']; ?>">Mark as Read</label>
                        <input type="checkbox" name="is_read" id="is_read-<?php echo $notification['id']; ?>" <?php echo $notification['is_read'] ? 'checked' : ''; ?>>
                    </div>
                    
                    <div class="form-group">
                        <label for="user_id-<?php echo $notification['id']; ?>">Specific User (Optional)</label>
                        <select name="user_id" id="user_id-<?php echo $notification['id']; ?>" class="form-control">
                            <option value="">All Users</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>" <?php echo ($notification['user_id'] == $user['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user['username'] . ' (' . $user['email'] . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Creation Time</label>
                        <p><?php echo date('F d, Y H:i:s', strtotime($notification['notification_time'])); ?></p>
                    </div>
                    
                    <?php if ($notification['updated_at'] !== $notification['created_at']): ?>
                    <div class="form-group">
                        <label>Last Updated</label>
                        <p><?php echo date('F d, Y H:i:s', strtotime($notification['updated_at'])); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <div class="form-group submit-row">
                        <button type="submit" name="update_general_notification" class="btn btn-primary">Update Notification</button>
                    </div>
                </form>
            </div>
        <?php endforeach; ?>
        
        <!-- User Notification Details Sections -->
        <?php foreach ($user_notifications as $notification): ?>
            <div class="admin-details" id="user-details-<?php echo $notification['id']; ?>">
                <h3>Edit User Message</h3>
                
                <button class="btn btn-danger delete-btn" data-id="<?php echo $notification['id']; ?>" data-type="user">Delete This Message</button>
                
                <form action="" method="POST" class="edit-form">
                    <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                    
                    <div class="form-group">
                        <label for="title-<?php echo $notification['id']; ?>">Message Title</label>
                        <input type="text" name="title" id="title-<?php echo $notification['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($notification['title']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="message-<?php echo $notification['id']; ?>">Message Text</label>
                        <textarea name="message" id="message-<?php echo $notification['id']; ?>" class="form-control" rows="5" required><?php echo htmlspecialchars($notification['message']); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Message Type</label>
                        <div class="type-selector">
                            <div class="type-option type-info <?php echo ($notification['type'] === 'info') ? 'active' : ''; ?>" data-value="info" data-id="<?php echo $notification['id']; ?>">
                                <i class="fas fa-info-circle"></i> Info
                            </div>
                            <div class="type-option type-success <?php echo ($notification['type'] === 'success') ? 'active' : ''; ?>" data-value="success" data-id="<?php echo $notification['id']; ?>">
                                <i class="fas fa-check-circle"></i> Success
                            </div>
                            <div class="type-option type-warning <?php echo ($notification['type'] === 'warning') ? 'active' : ''; ?>" data-value="warning" data-id="<?php echo $notification['id']; ?>">
                                <i class="fas fa-exclamation-triangle"></i> Warning
                            </div>
                            <div class="type-option type-danger <?php echo ($notification['type'] === 'danger') ? 'active' : ''; ?>" data-value="danger" data-id="<?php echo $notification['id']; ?>">
                                <i class="fas fa-times-circle"></i> Danger
                            </div>
                        </div>
                        <input type="hidden" name="type" id="type-input-<?php echo $notification['id']; ?>" value="<?php echo htmlspecialchars($notification['type']); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="is_read-user-<?php echo $notification['id']; ?>">Mark as Read</label>
                        <input type="checkbox" name="is_read" id="is_read-user-<?php echo $notification['id']; ?>" <?php echo $notification['is_read'] ? 'checked' : ''; ?>>
                    </div>
                    
                    <div class="form-group">
                        <label for="user_id-user-<?php echo $notification['id']; ?>">User</label>
                        <select name="user_id" id="user_id-user-<?php echo $notification['id']; ?>" class="form-control" required>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>" <?php echo ($notification['user_id'] == $user['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user['username'] . ' (' . $user['email'] . ')'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Creation Time</label>
                        <p><?php echo date('F d, Y H:i:s', strtotime($notification['created_at'])); ?></p>
                    </div>
                    
                    <div class="form-group submit-row">
                        <button type="submit" name="update_user_notification" class="btn btn-primary">Update Message</button>
                    </div>
                </form>
            </div>
        <?php endforeach; ?>
        
        <!-- Delete Confirmation Modal -->
        <div class="modal" id="deleteModal">
            <div class="modal-content">
                <div class="warning-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <h3 class="modal-title">Delete Notification</h3>
                <p class="modal-text">Are you sure you want to delete this notification from database?</p>
                <div class="modal-actions">
                    <form id="deleteForm" action="" method="POST">
                        <input type="hidden" name="notification_id" id="deleteNotificationId">
                        <input type="hidden" name="delete_type" id="deleteType">
                        <button type="submit" name="delete_general_notification" id="deleteGeneralBtn" class="btn btn-danger" style="display:none;">Yes, Delete General Notification</button>
                        <button type="submit" name="delete_user_notification" id="deleteUserBtn" class="btn btn-danger" style="display:none;">Yes, Delete User Message</button>
                    </form>
                    <button class="btn btn-primary" id="cancelDelete">Cancel</button>
                </div>
            </div>
        </div>
        
        <!-- New General Notification Modal -->
        <div class="modal" id="newGeneralModal">
            <div class="modal-content">
                <div class="new-admin-form">
                    <h3>Add New General Notification</h3>
                    <form action="" method="POST" class="edit-form">
                        <div class="form-group">
                            <label for="new-notification_title">Notification Title</label>
                            <input type="text" name="notification_title" id="new-notification_title" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-notification_text">Notification Text</label>
                            <textarea name="notification_text" id="new-notification_text" class="form-control" rows="5" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-is_read">Mark as Read</label>
                            <input type="checkbox" name="is_read" id="new-is_read">
                        </div>
                        
                        <div class="form-group">
                            <label for="new-user_id">Specific User (Optional)</label>
                            <select name="user_id" id="new-user_id" class="form-control">
                                <option value="">All Users</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['username'] . ' (' . $user['email'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group submit-row">
                            <button type="submit" name="create_general_notification" class="btn btn-success">Create Notification</button>
                            <button type="button" class="btn btn-danger" id="cancelAddGeneral">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- New User Message Modal -->
        <div class="modal" id="newUserModal">
            <div class="modal-content">
                <div class="new-admin-form">
                    <h3>Add New User Message</h3>
                    <form action="" method="POST" class="edit-form">
                        <div class="form-group">
                            <label for="new-title">Message Title</label>
                            <input type="text" name="title" id="new-title" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-message">Message Text</label>
                            <textarea name="message" id="new-message" class="form-control" rows="5" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label>Message Type</label>
                            <div class="type-selector">
                                <div class="type-option type-info active" data-value="info" data-id="new">
                                    <i class="fas fa-info-circle"></i> Info
                                </div>
                                <div class="type-option type-success" data-value="success" data-id="new">
                                    <i class="fas fa-check-circle"></i> Success
                                </div>
                                <div class="type-option type-warning" data-value="warning" data-id="new">
                                    <i class="fas fa-exclamation-triangle"></i> Warning
                                </div>
                                <div class="type-option type-danger" data-value="danger" data-id="new">
                                    <i class="fas fa-times-circle"></i> Danger
                                </div>
                            </div>
                            <input type="hidden" name="type" id="type-input-new" value="info">
                        </div>
                        
                        <div class="form-group">
                            <label for="new-is_read-user">Mark as Read</label>
                            <input type="checkbox" name="is_read" id="new-is_read-user">
                        </div>
                        
                        <div class="form-group">
                            <label for="new-user_id-user">User</label>
                            <select name="user_id" id="new-user_id-user" class="form-control" required>
                                <option value="">Select User</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['username'] . ' (' . $user['email'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group submit-row">
                            <button type="submit" name="create_user_notification" class="btn btn-success">Create Message</button>
                            <button type="button" class="btn btn-danger" id="cancelAddUser">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Tab navigation
            const tabBtns = document.querySelectorAll('.tab-btn');
            tabBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    // Remove active class from all buttons and content
                    tabBtns.forEach(b => b.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(content => {
                        content.classList.remove('active');
                    });
                    
                    // Add active class to clicked button and its content
                    this.classList.add('active');
                    document.getElementById(this.dataset.tab + '-tab').classList.add('active');
                    
                    // Reset cards and details when switching tabs
                    document.querySelectorAll('.admin-card').forEach(card => {
                        card.classList.remove('active');
                    });
                    
                    document.querySelectorAll('.admin-details').forEach(detail => {
                        detail.classList.remove('active');
                    });
                });
            });
            
            // Notification card click handler
            const notificationCards = document.querySelectorAll('.admin-card');
            notificationCards.forEach(card => {
                card.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const type = this.getAttribute('data-type');
                    
                    // Hide all details sections
                    document.querySelectorAll('.admin-details').forEach(detail => {
                        detail.classList.remove('active');
                    });
                    
                    // Remove active class from all cards
                    notificationCards.forEach(c => {
                        c.classList.remove('active');
                    });
                    
                    // Show the clicked notification's details
                    document.getElementById(type + '-details-' + id).classList.add('active');
                    
                    // Add active class to the clicked card
                    this.classList.add('active');
                    
                    // Scroll to the details section
                    document.getElementById(type + '-details-' + id).scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                });
            });
            
            // Delete button click handler
            const deleteButtons = document.querySelectorAll('.delete-btn');
            const deleteModal = document.getElementById('deleteModal');
            const deleteForm = document.getElementById('deleteForm');
            const deleteNotificationId = document.getElementById('deleteNotificationId');
            const deleteType = document.getElementById('deleteType');
            const deleteGeneralBtn = document.getElementById('deleteGeneralBtn');
            const deleteUserBtn = document.getElementById('deleteUserBtn');
            const cancelDelete = document.getElementById('cancelDelete');
            
            deleteButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const id = this.getAttribute('data-id');
                    const type = this.getAttribute('data-type');
                    
                    deleteNotificationId.value = id;
                    deleteType.value = type;
                    
                    // Show the appropriate delete button
                    if (type === 'general') {
                        deleteGeneralBtn.style.display = 'inline-block';
                        deleteUserBtn.style.display = 'none';
                    } else {
                        deleteGeneralBtn.style.display = 'none';
                        deleteUserBtn.style.display = 'inline-block';
                    }
                    
                    deleteModal.style.display = 'flex';
                });
            });
            
            // Cancel delete button
            cancelDelete.addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            // Type selector handling for user notifications
            const typeOptions = document.querySelectorAll('.type-option');
            typeOptions.forEach(option => {
                option.addEventListener('click', function() {
                    const value = this.getAttribute('data-value');
                    const id = this.getAttribute('data-id');
                    
                    // Remove active class from all options in this group
                    document.querySelectorAll(`.type-option[data-id="${id}"]`).forEach(opt => {
                        opt.classList.remove('active');
                    });
                    
                    // Add active class to clicked option
                    this.classList.add('active');
                    
                    // Update the hidden input value
                    document.getElementById('type-input-' + id).value = value;
                });
            });
            
            // Add new general notification button
            const addGeneralBtn = document.getElementById('addGeneralBtn');
            const newGeneralModal = document.getElementById('newGeneralModal');
            const cancelAddGeneral = document.getElementById('cancelAddGeneral');
            
            addGeneralBtn.addEventListener('click', function() {
                newGeneralModal.style.display = 'flex';
            });
            
            // Cancel add general notification button
            cancelAddGeneral.addEventListener('click', function() {
                newGeneralModal.style.display = 'none';
            });
            
            // Add new user message button
            const addUserBtn = document.getElementById('addUserBtn');
            const newUserModal = document.getElementById('newUserModal');
            const cancelAddUser = document.getElementById('cancelAddUser');
            
            addUserBtn.addEventListener('click', function() {
                newUserModal.style.display = 'flex';
            });
            
            // Cancel add user message button
            cancelAddUser.addEventListener('click', function() {
                newUserModal.style.display = 'none';
            });
            
            // Close modals if clicked outside
            window.addEventListener('click', function(e) {
                if (e.target === deleteModal) {
                    deleteModal.style.display = 'none';
                }
                if (e.target === newGeneralModal) {
                    newGeneralModal.style.display = 'none';
                }
                if (e.target === newUserModal) {
                    newUserModal.style.display = 'none';
                }
            });
            
            // Close alerts
            const closeAlerts = document.querySelectorAll('.close-alert');
            closeAlerts.forEach(btn => {
                btn.addEventListener('click', function() {
                    this.parentElement.style.display = 'none';
                });
            });
        });
    </script>
</body>
</html>