<?php
define('SECURE_ACCESS', true);

$pageTitle = "My Notifications";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

$user = getCurrentUser();

$error = '';
$success = '';

// 1. Handle Mark All Read Action
if (isset($_GET['action']) && $_GET['action'] === 'read_all') {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: notifications");
        exit();
    }
    try {
        $stmt = $pdo->prepare("UPDATE notifications SET is_read = TRUE WHERE user_id = ? AND channels_sent LIKE '%in_app%'");
        $stmt->execute([$user['id']]);
        $_SESSION['flash_success'] = "All notifications marked as read.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to update notifications: " . $e->getMessage();
    }
    header("Location: notifications");
    exit();
}

// 2. Handle Delete Action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: notifications");
        exit();
    }
    $notifId = (int)$_GET['id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ?");
        $stmt->execute([$notifId, $user['id']]);
        $_SESSION['flash_success'] = "Notification deleted successfully.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to delete notification: " . $e->getMessage();
    }
    header("Location: notifications");
    exit();
}

// 3. Fetch User In-App Notifications
$notifications = [];
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$total_records = 0;
$total_pages = 0;
$has_unread = false;

try {
    // Count query
    $stmt_count = $pdo->prepare("
        SELECT COUNT(*) FROM notifications 
        WHERE user_id = ? AND channels_sent LIKE '%in_app%'
    ");
    $stmt_count->execute([$user['id']]);
    $total_records = (int)$stmt_count->fetchColumn() ?: 0;
    $total_pages = ceil($total_records / $limit);

    // Fetch paginated
    $stmt = $pdo->prepare("
        SELECT * FROM notifications 
        WHERE user_id = ? AND channels_sent LIKE '%in_app%' 
        ORDER BY created_at DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute([$user['id']]);
    $notifications = $stmt->fetchAll();

    // Check for unread alerts
    $stmt_unread = $pdo->prepare("
        SELECT COUNT(*) FROM notifications 
        WHERE user_id = ? AND is_read = FALSE AND channels_sent LIKE '%in_app%'
    ");
    $stmt_unread->execute([$user['id']]);
    $has_unread = ((int)$stmt_unread->fetchColumn() > 0);
} catch (PDOException $e) {
    $error = "Failed to load notifications: " . $e->getMessage();
}

include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">My Notifications</h1>
        <p class="text-muted mb-0">View and manage your inbox alerts and reminder updates.</p>
    </div>
    <?php if ($has_unread): ?>
        <a href="notifications?action=read_all&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-outline-primary btn-sm px-3 fw-bold">
            <i class="bi bi-check-all me-1"></i> Mark All as Read
        </a>
    <?php endif; ?>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-0">
        <?php if (empty($notifications)): ?>
            <div class="text-center py-5 text-muted">
                <i class="bi bi-bell-slash fs-1 mb-3 text-secondary"></i>
                <h5 class="fw-semibold text-dark">No notifications yet</h5>
                <p class="mb-0 small">When you receive account updates, event invitations, or payment logs, they will appear here.</p>
            </div>
        <?php else: ?>
            <div class="list-group list-group-flush">
                <?php foreach ($notifications as $n): ?>
                    <div class="list-group-item p-4 border-bottom bg-white" style="transition: background-color 0.2s;">
                        <div class="d-flex justify-content-between align-items-start gap-3">
                            <div class="d-flex gap-3">
                                <div class="flex-shrink-0 mt-1">
                                    <?php if (!$n['is_read']): ?>
                                        <span class="d-block bg-primary rounded-circle" style="width: 10px; height: 10px;" title="Unread"></span>
                                    <?php else: ?>
                                        <span class="d-block bg-secondary bg-opacity-25 rounded-circle" style="width: 10px; height: 10px;"></span>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <h6 class="fw-bold mb-1 <?php echo !$n['is_read'] ? 'text-primary' : 'text-dark'; ?>">
                                        <?php echo htmlspecialchars($n['title']); ?>
                                    </h6>
                                    <p class="text-secondary mb-0 small lh-sm" style="font-size: 0.9rem;"><?php echo htmlspecialchars($n['message']); ?></p>
                                    <span class="text-muted font-monospace d-block mt-2" style="font-size: 0.75rem;">
                                        <i class="bi bi-clock me-1"></i><?php echo date('F d, Y - H:i', strtotime($n['created_at'])); ?>
                                    </span>
                                </div>
                            </div>
                            <a href="notifications?action=delete&id=<?php echo $n['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-outline-danger btn-sm border-0 py-1 px-2 text-danger hover-bg-danger" onclick="return confirm('Delete this notification?');" title="Delete notification">
                                <i class="bi bi-trash-fill"></i>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php if ($total_pages > 1): ?>
        <div class="card-footer bg-light border-top py-3 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
            <div class="small text-secondary font-monospace">
                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> alerts
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>"><i class="bi bi-chevron-left"></i></a>
                    </li>
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $page + 2);
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                        <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>"><i class="bi bi-chevron-right"></i></a>
                    </li>
                </ul>
            </nav>
        </div>
    <?php endif; ?>
</div>

<?php
include __DIR__ . '/../includes/footer.php';
?>
