<?php
/**
 * Notifications Page
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Notifications';
$userId = getCurrentUserId();
$success = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $action = $_POST['action'] ?? '';
    $db = getDB();
    
    if ($action === 'mark_read') {
        $notifId = (int)($_POST['notif_id'] ?? 0);
        if ($notifId > 0) {
            $stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?");
            $stmt->execute([$notifId, $userId]);
        }
    } elseif ($action === 'mark_all_read') {
        $stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?");
        $stmt->execute([$userId]);
        $success = 'All notifications marked as read.';
    } elseif ($action === 'delete') {
        $notifId = (int)($_POST['notif_id'] ?? 0);
        if ($notifId > 0) {
            $stmt = $db->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ?");
            $stmt->execute([$notifId, $userId]);
        }
    } elseif ($action === 'clear_all') {
        $stmt = $db->prepare("DELETE FROM notifications WHERE user_id = ?");
        $stmt->execute([$userId]);
        $success = 'All notifications cleared.';
    }
}

// Get filter
$filter = $_GET['filter'] ?? 'all';

// Build query
$db = getDB();
$where = "user_id = ?";
$params = [$userId];

if ($filter === 'unread') {
    $where .= " AND is_read = 0";
}

// Get notifications
$stmt = $db->prepare("
    SELECT * FROM notifications 
    WHERE $where 
    ORDER BY created_at DESC 
    LIMIT 100
");
$stmt->execute($params);
$notifications = $stmt->fetchAll();

// Get counts
$stmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ?");
$stmt->execute([$userId]);
$totalCount = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
$stmt->execute([$userId]);
$unreadCount = $stmt->fetchColumn();

include '../templates/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">
                    <i class="fas fa-bell"></i> Notifications
                    <?php if ($unreadCount > 0): ?>
                        <span class="badge bg-danger"><?php echo $unreadCount; ?></span>
                    <?php endif; ?>
                </h1>
                <div class="btn-toolbar">
                    <?php if ($unreadCount > 0): ?>
                    <form method="POST" action="" style="display: inline;">
                        <?php echo csrfField(); ?>
                        <input type="hidden" name="action" value="mark_all_read">
                        <button type="submit" class="btn btn-outline-primary me-2">
                            <i class="fas fa-check-double"></i> Mark All Read
                        </button>
                    </form>
                    <?php endif; ?>
                    <?php if ($totalCount > 0): ?>
                    <form method="POST" action="" style="display: inline;" 
                          onsubmit="return confirm('Are you sure you want to clear all notifications?')">
                        <?php echo csrfField(); ?>
                        <input type="hidden" name="action" value="clear_all">
                        <button type="submit" class="btn btn-outline-danger">
                            <i class="fas fa-trash"></i> Clear All
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Filter Tabs -->
            <ul class="nav nav-pills mb-4">
                <li class="nav-item">
                    <a class="nav-link <?php echo $filter === 'all' ? 'active' : ''; ?>" href="?filter=all">
                        All (<?php echo $totalCount; ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $filter === 'unread' ? 'active' : ''; ?>" href="?filter=unread">
                        Unread (<?php echo $unreadCount; ?>)
                    </a>
                </li>
            </ul>

            <!-- Notifications List -->
            <div class="card shadow">
                <div class="card-body p-0">
                    <?php if (empty($notifications)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-bell-slash fa-4x text-muted mb-3"></i>
                            <h5>No Notifications</h5>
                            <p class="text-muted">You're all caught up!</p>
                        </div>
                    <?php else: ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($notifications as $notif): ?>
                            <div class="list-group-item <?php echo !$notif['is_read'] ? 'bg-light' : ''; ?>">
                                <div class="d-flex w-100 justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <div class="d-flex align-items-center mb-2">
                                            <?php
                                            $iconClass = 'fa-bell';
                                            $iconColor = 'text-primary';
                                            
                                            switch ($notif['type']) {
                                                case 'collaboration_invite':
                                                    $iconClass = 'fa-users';
                                                    $iconColor = 'text-info';
                                                    break;
                                                case 'study_update':
                                                    $iconClass = 'fa-flask';
                                                    $iconColor = 'text-success';
                                                    break;
                                                case 'message':
                                                    $iconClass = 'fa-envelope';
                                                    $iconColor = 'text-warning';
                                                    break;
                                                case 'connection_request':
                                                    $iconClass = 'fa-user-plus';
                                                    $iconColor = 'text-primary';
                                                    break;
                                            }
                                            ?>
                                            <i class="fas <?php echo $iconClass; ?> <?php echo $iconColor; ?> me-2"></i>
                                            <h6 class="mb-0">
                                                <?php echo e($notif['title']); ?>
                                                <?php if (!$notif['is_read']): ?>
                                                    <span class="badge bg-primary ms-2">New</span>
                                                <?php endif; ?>
                                            </h6>
                                        </div>
                                        <p class="mb-1"><?php echo e($notif['message']); ?></p>
                                        <small class="text-muted">
                                            <i class="fas fa-clock"></i> <?php echo timeAgo($notif['created_at']); ?>
                                        </small>
                                    </div>
                                    <div class="btn-group ms-3">
                                        <?php if ($notif['link']): ?>
                                            <a href="<?php echo e($notif['link']); ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                        <?php endif; ?>
                                        <?php if (!$notif['is_read']): ?>
                                            <form method="POST" action="" style="display: inline;">
                                                <?php echo csrfField(); ?>
                                                <input type="hidden" name="action" value="mark_read">
                                                <input type="hidden" name="notif_id" value="<?php echo $notif['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-success" title="Mark as read">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                        <form method="POST" action="" style="display: inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="notif_id" value="<?php echo $notif['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

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