<?php
$page_title = "Notifications Management";
require_once 'header.php';

$db = Database::getInstance()->connect();
$notificationHelper = new InvestmentFunctions();

// Handle send notification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_notification'])) {
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $type = $_POST['type'];
    $send_to = $_POST['send_to'];
    $user_ids = $_POST['user_ids'] ?? '';
    
    if (empty($title) || empty($message)) {
        $error = "Title and message are required";
    } else {
        try {
            $db->beginTransaction();
            $sent_count = 0;
            
            // Determine recipients
            $email_subject = $title;
            $email_body = "<html><body>" .
                "<h2>" . htmlspecialchars($title) . "</h2>" .
                "<p>" . nl2br(htmlspecialchars($message)) . "</p>" .
                "<p>Regards,<br>" . SITE_NAME . " Team</p>" .
                "</body></html>";

            if ($send_to == 'all_users') {
                // Send to all active users
                $users_stmt = $db->query("SELECT id, email FROM users WHERE account_status = 'active' AND email <> ''");
                $users = $users_stmt->fetchAll();

                foreach ($users as $user) {
                    $insert_stmt = $db->prepare(" 
                        INSERT INTO notifications (user_id, type, title, message, data)
                        VALUES (?, ?, ?, ?, ?)
                    ");

                    $insert_stmt->execute([
                        $user['id'],
                        $type,
                        $title,
                        $message,
                        json_encode(['sent_by_admin' => $_SESSION['admin_id']])
                    ]);

                    if (!empty($user['email'])) {
                        $notificationHelper->sendEmail($user['email'], $email_subject, $email_body);
                    }
                    $sent_count++;
                }

            } elseif ($send_to == 'specific_users' && !empty($user_ids)) {
                // Send to specific users
                $user_ids_array = array_filter(array_map('intval', explode(',', $user_ids)));
                if (!empty($user_ids_array)) {
                    $placeholders = implode(',', array_fill(0, count($user_ids_array), '?'));
                    $users_stmt = $db->prepare("SELECT id, email FROM users WHERE id IN ($placeholders) AND account_status = 'active'");
                    $users_stmt->execute($user_ids_array);
                    $users = $users_stmt->fetchAll();

                    foreach ($users as $user) {
                        $insert_stmt = $db->prepare(" 
                            INSERT INTO notifications (user_id, type, title, message, data)
                            VALUES (?, ?, ?, ?, ?)
                        ");

                        $insert_stmt->execute([
                            $user['id'],
                            $type,
                            $title,
                            $message,
                            json_encode(['sent_by_admin' => $_SESSION['admin_id']])
                        ]);

                        if (!empty($user['email'])) {
                            $notificationHelper->sendEmail($user['email'], $email_subject, $email_body);
                        }
                        $sent_count++;
                    }
                }

            } elseif ($send_to == 'with_balance') {
                // Send to users with minimum balance
                $min_balance = floatval($_POST['min_balance']);
                $users_stmt = $db->prepare(" 
                    SELECT id, email FROM users 
                    WHERE account_status = 'active' AND balance >= ? AND email <> ''
                ");
                $users_stmt->execute([$min_balance]);
                $users = $users_stmt->fetchAll();

                foreach ($users as $user) {
                    $insert_stmt = $db->prepare(" 
                        INSERT INTO notifications (user_id, type, title, message, data)
                        VALUES (?, ?, ?, ?, ?)
                    ");

                    $insert_stmt->execute([
                        $user['id'],
                        $type,
                        $title,
                        $message,
                        json_encode(['sent_by_admin' => $_SESSION['admin_id'], 'min_balance' => $min_balance])
                    ]);

                    if (!empty($user['email'])) {
                        $notificationHelper->sendEmail($user['email'], $email_subject, $email_body);
                    }
                    $sent_count++;
                }

            } elseif ($send_to == 'with_investments') {
                // Send to users with active investments
                $users_stmt = $db->query(" 
                    SELECT DISTINCT u.id, u.email
                    FROM users u
                    INNER JOIN investments i ON u.id = i.user_id
                    WHERE i.status = 'running' AND u.account_status = 'active' AND u.email <> ''
                ");
                $users = $users_stmt->fetchAll();

                foreach ($users as $user) {
                    $insert_stmt = $db->prepare(" 
                        INSERT INTO notifications (user_id, type, title, message, data)
                        VALUES (?, ?, ?, ?, ?)
                    ");

                    $insert_stmt->execute([
                        $user['id'],
                        $type,
                        $title,
                        $message,
                        json_encode(['sent_by_admin' => $_SESSION['admin_id']])
                    ]);

                    if (!empty($user['email'])) {
                        $notificationHelper->sendEmail($user['email'], $email_subject, $email_body);
                    }
                }
            }
            
            // Log the action
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (admin_id, action, description, ip_address, user_agent, details, created_at)
                VALUES (?, 'notification_sent', 'Notification sent to users', ?, ?, ?, NOW())
            ");

            $log_stmt->execute([
                $_SESSION['admin_id'],
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                json_encode([
                    'title' => $title,
                    'type' => $type,
                    'sent_to' => $send_to,
                    'sent_count' => $sent_count
                ])
            ]);
            
            $db->commit();
            $success = "Notification sent successfully to $sent_count users!";
            
        } catch (Exception $e) {
            $db->rollBack();
            $error = "Failed to send notification: " . $e->getMessage();
        }
    }
}

// Handle bulk actions
if (isset($_POST['bulk_action'])) {
    $action = $_POST['bulk_action'];
    $notification_ids = $_POST['notification_ids'] ?? [];
    
    if (empty($notification_ids)) {
        $error = "Please select notifications to perform action";
    } else {
        $ids = array_map('intval', $notification_ids);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        
        try {
            if ($action == 'delete') {
                $delete_stmt = $db->prepare("DELETE FROM notifications WHERE id IN ($placeholders)");
                $delete_stmt->execute($ids);
                $success = count($ids) . " notifications deleted successfully!";
            } elseif ($action == 'mark_read') {
                $update_stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE id IN ($placeholders)");
                $update_stmt->execute($ids);
                $success = count($ids) . " notifications marked as read!";
            }
        } catch (Exception $e) {
            $error = "Failed to perform action: " . $e->getMessage();
        }
    }
}

// Get notification statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_notifications,
        SUM(CASE WHEN is_read = 1 THEN 1 ELSE 0 END) as read_notifications,
        SUM(CASE WHEN is_read = 0 THEN 1 ELSE 0 END) as unread_notifications,
        COUNT(DISTINCT user_id) as affected_users,
        (SELECT COUNT(*) FROM notifications WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)) as recent_notifications
    FROM notifications
";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();

// Get recent notifications
$recent_sql = "
    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 
    LIMIT 50
";

$recent_stmt = $db->query($recent_sql);
$recent_notifications = $recent_stmt->fetchAll();

// Get user statistics for targeting
$user_stats_sql = "
    SELECT 
        (SELECT COUNT(*) FROM users WHERE account_status = 'active') as active_users,
        (SELECT COUNT(*) FROM users WHERE balance > 0) as users_with_balance,
        (SELECT COUNT(DISTINCT user_id) FROM investments WHERE status = 'running') as users_with_investments
";

$user_stats_stmt = $db->query($user_stats_sql);
$user_stats = $user_stats_stmt->fetch();
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Notifications Management</h1>
        <p class="text-gray-600">Send and manage system notifications</p>
    </div>

    <!-- Messages -->
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        <?php echo $success; ?>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Notifications</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total_notifications']); ?></h3>
                </div>
                <i class="fas fa-bell text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Unread Notifications</p>
                    <h3 class="text-2xl font-bold text-red-600"><?php echo number_format($stats['unread_notifications']); ?></h3>
                </div>
                <i class="fas fa-envelope text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Affected Users</p>
                    <h3 class="text-2xl font-bold text-blue-600"><?php echo number_format($stats['affected_users']); ?></h3>
                </div>
                <i class="fas fa-users text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Recent (7 days)</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($stats['recent_notifications']); ?></h3>
                </div>
                <i class="fas fa-clock text-green-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Send Notification Form -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <h3 class="text-lg font-bold mb-4">Send New Notification</h3>
        <form method="POST" action="" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Notification Title *</label>
                    <input type="text" name="title" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Enter notification title">
                </div>
                
                <div>
                    <label class="block text-gray-700 font-medium mb-2">Notification Type</label>
                    <select name="type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="info">Information</option>
                        <option value="success">Success</option>
                        <option value="warning">Warning</option>
                        <option value="error">Error</option>
                        <option value="promotion">Promotion</option>
                        <option value="update">Update</option>
                    </select>
                </div>
            </div>
            
            <div>
                <label class="block text-gray-700 font-medium mb-2">Message *</label>
                <textarea name="message" rows="4" required
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                          placeholder="Enter notification message..."></textarea>
                <p class="text-sm text-gray-500 mt-1">Supports basic HTML formatting</p>
            </div>
            
            <!-- Recipient Selection -->
            <div>
                <label class="block text-gray-700 font-medium mb-2">Send To</label>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <input type="radio" name="send_to" value="all_users" checked class="mr-3">
                        <div>
                            <p class="font-medium">All Active Users</p>
                            <p class="text-sm text-gray-500"><?php echo number_format($user_stats['active_users']); ?> users</p>
                        </div>
                    </label>
                    
                    <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <input type="radio" name="send_to" value="specific_users" class="mr-3">
                        <div>
                            <p class="font-medium">Specific Users</p>
                            <p class="text-sm text-gray-500">By User IDs</p>
                        </div>
                    </label>
                    
                    <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <input type="radio" name="send_to" value="with_balance" class="mr-3">
                        <div>
                            <p class="font-medium">Users with Balance</p>
                            <p class="text-sm text-gray-500"><?php echo number_format($user_stats['users_with_balance']); ?> users</p>
                        </div>
                    </label>
                    
                    <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                        <input type="radio" name="send_to" value="with_investments" class="mr-3">
                        <div>
                            <p class="font-medium">Active Investors</p>
                            <p class="text-sm text-gray-500"><?php echo number_format($user_stats['users_with_investments']); ?> users</p>
                        </div>
                    </label>
                </div>
            </div>
            
            <!-- Conditional Fields -->
            <div id="specificUsersField" class="hidden">
                <label class="block text-gray-700 font-medium mb-2">User IDs (comma-separated)</label>
                <input type="text" name="user_ids" 
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                       placeholder="e.g., 1,5,23,42">
            </div>
            
            <div id="minBalanceField" class="hidden">
                <label class="block text-gray-700 font-medium mb-2">Minimum Balance ($)</label>
                <input type="number" step="0.01" name="min_balance" value="0"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
            </div>
            
            <!-- Additional Options -->
            <div class="border-t pt-6">
                <div class="space-y-3">
                    <label class="flex items-center">
                        <input type="checkbox" name="send_email" value="1" checked class="mr-3">
                        <span class="text-gray-700">Also send as email</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" name="urgent" value="1" class="mr-3">
                        <span class="text-gray-700">Mark as urgent</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" name="schedule" value="1" id="scheduleCheckbox" class="mr-3">
                        <span class="text-gray-700">Schedule for later</span>
                    </label>
                    
                    <div id="scheduleField" class="hidden">
                        <label class="block text-gray-700 font-medium mb-2">Schedule Date & Time</label>
                        <input type="datetime-local" name="schedule_time" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                </div>
            </div>
            
            <div class="border-t pt-6">
                <button type="submit" name="send_notification" 
                        class="w-full bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:opacity-90">
                    <i class="fas fa-paper-plane mr-2"></i>Send Notification
                </button>
            </div>
        </form>
    </div>

    <!-- Recent Notifications -->
    <div class="bg-white rounded-xl shadow">
        <div class="p-6 border-b flex justify-between items-center">
            <h3 class="text-lg font-bold">Recent Notifications</h3>
            
            <!-- Bulk Actions -->
            <form method="POST" action="" class="flex items-center space-x-2" id="bulkForm">
                <select name="bulk_action" class="px-3 py-2 border border-gray-300 rounded-lg">
                    <option value="">Bulk Actions</option>
                    <option value="mark_read">Mark as Read</option>
                    <option value="delete">Delete</option>
                </select>
                <button type="submit" class="bg-gray-800 text-white px-4 py-2 rounded-lg hover:bg-gray-900">
                    Apply
                </button>
            </form>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left" style="width: 30px;">
                            <input type="checkbox" id="selectAll">
                        </th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Title</th>
                        <th class="p-4 text-left">Type</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Date</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($recent_notifications as $notification): ?>
                    <tr class="hover:bg-gray-50 <?php echo !$notification['is_read'] ? 'bg-blue-50' : ''; ?>">
                        <td class="p-4">
                            <input type="checkbox" name="notification_ids[]" value="<?php echo $notification['id']; ?>" class="notification-checkbox">
                        </td>
                        <td class="p-4">
                            <?php if ($notification['user_id']): ?>
                            <p class="font-medium"><?php echo htmlspecialchars($notification['username'] ?? 'User #' . $notification['user_id']); ?></p>
                            <p class="text-sm text-gray-500">ID: <?php echo $notification['user_id']; ?></p>
                            <?php else: ?>
                            <span class="text-gray-500">System</span>
                            <?php endif; ?>
                        </td>
                        <td class="p-4">
                            <p class="font-medium"><?php echo htmlspecialchars($notification['title']); ?></p>
                            <p class="text-sm text-gray-500 truncate max-w-xs"><?php echo htmlspecialchars(substr($notification['message'], 0, 100)); ?>...</p>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $notification['type'] == 'success' ? 'bg-green-100 text-green-800' :
                                    ($notification['type'] == 'warning' ? 'bg-yellow-100 text-yellow-800' :
                                    ($notification['type'] == 'error' ? 'bg-red-100 text-red-800' :
                                    'bg-blue-100 text-blue-800')); ?>">
                                <?php echo ucfirst($notification['type']); ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $notification['is_read'] ? 'bg-gray-100 text-gray-800' : 'bg-red-100 text-red-800'; ?>">
                                <?php echo $notification['is_read'] ? 'Read' : 'Unread'; ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <p><?php echo date('M d, Y', strtotime($notification['created_at'])); ?></p>
                            <p class="text-sm text-gray-500"><?php echo date('H:i:s', strtotime($notification['created_at'])); ?></p>
                        </td>
                        <td class="p-4">
                            <button onclick="viewNotification(<?php echo $notification['id']; ?>)" 
                                    class="text-blue-600 hover:text-blue-800 text-sm font-medium mr-3">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button onclick="resendNotification(<?php echo $notification['id']; ?>)" 
                                    class="text-green-600 hover:text-green-800 text-sm font-medium mr-3">
                                <i class="fas fa-redo"></i>
                            </button>
                            <button onclick="deleteNotification(<?php echo $notification['id']; ?>)" 
                                    class="text-red-600 hover:text-red-800 text-sm font-medium">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if (count($recent_notifications) >= 50): ?>
        <div class="p-6 border-t text-center">
            <a href="notifications-list.php" class="text-blue-600 hover:text-blue-800">
                View All Notifications →
            </a>
        </div>
        <?php endif; ?>
    </div>

    <!-- Notification Templates -->
    <div class="mt-6 bg-white rounded-xl shadow p-6">
        <h3 class="text-lg font-bold mb-4">Notification Templates</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <button onclick="useTemplate('welcome')" class="bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                <i class="fas fa-user-plus text-purple-600 text-xl mb-2"></i>
                <p class="font-semibold">Welcome Message</p>
                <p class="text-sm text-gray-600">Welcome new users</p>
            </button>
            
            <button onclick="useTemplate('deposit')" class="bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                <i class="fas fa-money-bill-wave text-green-600 text-xl mb-2"></i>
                <p class="font-semibold">Deposit Reminder</p>
                <p class="text-sm text-gray-600">Remind users to deposit</p>
            </button>
            
            <button onclick="useTemplate('investment')" class="bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                <i class="fas fa-chart-line text-blue-600 text-xl mb-2"></i>
                <p class="font-semibold">Investment Alert</p>
                <p class="text-sm text-gray-600">New investment opportunities</p>
            </button>
            
            <button onclick="useTemplate('promotion')" class="bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                <i class="fas fa-gift text-red-600 text-xl mb-2"></i>
                <p class="font-semibold">Promotion</p>
                <p class="text-sm text-gray-600">Special offers & bonuses</p>
            </button>
            
            <button onclick="useTemplate('maintenance')" class="bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                <i class="fas fa-tools text-yellow-600 text-xl mb-2"></i>
                <p class="font-semibold">Maintenance Alert</p>
                <p class="text-sm text-gray-600">System maintenance notice</p>
            </button>
            
            <button onclick="useTemplate('update')" class="bg-gray-100 hover:bg-gray-200 p-4 rounded-lg text-left">
                <i class="fas fa-sync text-purple-600 text-xl mb-2"></i>
                <p class="font-semibold">System Update</p>
                <p class="text-sm text-gray-600">New features or updates</p>
            </button>
        </div>
    </div>
</div>

<!-- View Notification Modal -->
<div id="notificationModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl">
            <div class="p-6 border-b">
                <h3 id="modalTitle" class="text-xl font-bold"></h3>
            </div>
            <div class="p-6 max-h-[60vh] overflow-y-auto">
                <div id="modalContent"></div>
            </div>
            <div class="p-6 border-t">
                <button onclick="closeModal()" 
                        class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Show/hide conditional fields
document.querySelectorAll('input[name="send_to"]').forEach(radio => {
    radio.addEventListener('change', function() {
        document.getElementById('specificUsersField').classList.add('hidden');
        document.getElementById('minBalanceField').classList.add('hidden');
        
        if (this.value === 'specific_users') {
            document.getElementById('specificUsersField').classList.remove('hidden');
        } else if (this.value === 'with_balance') {
            document.getElementById('minBalanceField').classList.remove('hidden');
        }
    });
});

// Show/hide schedule field
document.getElementById('scheduleCheckbox').addEventListener('change', function() {
    document.getElementById('scheduleField').classList.toggle('hidden', !this.checked);
});

// Bulk selection
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.notification-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
});

// View notification
function viewNotification(id) {
    $.ajax({
        url: '../api/get-notification.php',
        method: 'GET',
        data: { id: id },
        success: function(response) {
            const notification = JSON.parse(response);
            document.getElementById('modalTitle').textContent = notification.title;
            
            let content = `
                <div class="space-y-4">
                    <div>
                        <p class="text-sm text-gray-600">Type</p>
                        <p class="font-medium">${notification.type}</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Recipient</p>
                        <p class="font-medium">${notification.username || 'System'}</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Status</p>
                        <p class="font-medium ${notification.is_read ? 'text-green-600' : 'text-red-600'}">
                            ${notification.is_read ? 'Read' : 'Unread'}
                        </p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Message</p>
                        <div class="bg-gray-50 p-4 rounded-lg mt-2">
                            ${notification.message}
                        </div>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Sent Date</p>
                        <p class="font-medium">${notification.created_at}</p>
                    </div>
                </div>
            `;
            
            document.getElementById('modalContent').innerHTML = content;
            document.getElementById('notificationModal').classList.remove('hidden');
        }
    });
}

function closeModal() {
    document.getElementById('notificationModal').classList.add('hidden');
}

// Resend notification
function resendNotification(id) {
    if (confirm('Resend this notification?')) {
        $.ajax({
            url: '../api/resend-notification.php',
            method: 'POST',
            data: { id: id },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

// Delete notification
function deleteNotification(id) {
    if (confirm('Delete this notification?')) {
        $.ajax({
            url: '../api/delete-notification.php',
            method: 'POST',
            data: { id: id },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

// Use template
function useTemplate(template) {
    const templates = {
        welcome: {
            title: 'Welcome to <?php echo SITE_NAME; ?>!',
            message: 'Dear user, welcome to our investment platform. Start your journey to financial freedom today!',
            type: 'success'
        },
        deposit: {
            title: 'Deposit Bonus Available!',
            message: 'Make a deposit today and get a special bonus! Limited time offer.',
            type: 'promotion'
        },
        investment: {
            title: 'New Investment Opportunity',
            message: 'Check out our new investment plan with higher returns!',
            type: 'info'
        },
        promotion: {
            title: 'Special Promotion!',
            message: 'Get 20% bonus on your next deposit. Promo code: GROW20',
            type: 'promotion'
        },
        maintenance: {
            title: 'Scheduled Maintenance',
            message: 'The platform will be undergoing maintenance on Saturday. Service may be temporarily unavailable.',
            type: 'warning'
        },
        update: {
            title: 'System Update',
            message: 'We have updated our platform with new features. Check them out!',
            type: 'info'
        }
    };
    
    const selected = templates[template];
    if (selected) {
        document.querySelector('input[name="title"]').value = selected.title;
        document.querySelector('textarea[name="message"]').value = selected.message;
        document.querySelector('select[name="type"]').value = selected.type;
        
        // Scroll to form
        document.querySelector('input[name="title"]').scrollIntoView({ behavior: 'smooth' });
    }
}

// Auto-save draft
let autoSaveTimer;
document.querySelector('textarea[name="message"]').addEventListener('input', function() {
    clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(() => {
        const draft = {
            title: document.querySelector('input[name="title"]').value,
            message: this.value,
            type: document.querySelector('select[name="type"]').value,
            send_to: (document.querySelector('input[name="send_to"]:checked') || {}).value
        };
        localStorage.setItem('notification_draft', JSON.stringify(draft));
    }, 1000);
});

// Load draft on page load
window.addEventListener('load', function() {
    const draft = JSON.parse(localStorage.getItem('notification_draft'));
    if (draft) {
        if (confirm('Load saved draft?')) {
            document.querySelector('input[name="title"]').value = draft.title || '';
            document.querySelector('textarea[name="message"]').value = draft.message || '';
            document.querySelector('select[name="type"]').value = draft.type || 'info';
            if (draft.send_to) {
                const sendToInput = document.querySelector(`input[name="send_to"][value="${draft.send_to}"]`);
                if (sendToInput) {
                    sendToInput.checked = true;
                }
            }
        }
    }
});
</script>

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