<?php
/**
 * Notifications Page
 * GHAMECC Job Portal
 * 
 * This page displays all notifications for the current user with options to
 * mark as read, delete, and filter by notification type.
 */

// Include required files
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/notifications-library.php';

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

// Get current user ID
$userId = $_SESSION['user_id'];

// Process actions
if (isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'mark_read' && isset($_POST['notification_id'])) {
        $notificationId = (int)$_POST['notification_id'];
        markNotificationAsRead($notificationId, $userId);
    } elseif ($action === 'mark_all_read') {
        markAllNotificationsAsRead($userId);
    } elseif ($action === 'delete' && isset($_POST['notification_id'])) {
        $notificationId = (int)$_POST['notification_id'];
        deleteNotification($notificationId, $userId);
    } elseif ($action === 'delete_all') {
        deleteAllNotifications($userId);
    }
    
    // Redirect to prevent form resubmission
    header('Location: notifications.php' . (isset($_GET['type']) ? '?type=' . urlencode($_GET['type']) : ''));
    exit;
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filter by type
$type = isset($_GET['type']) ? $_GET['type'] : '';
$typeFilter = '';
$typeParams = [];

if (!empty($type)) {
    $typeFilter = " AND type = ?";
    $typeParams = [$type];
}

// Get total count for pagination
$countQuery = "SELECT COUNT(*) as count FROM notifications WHERE user_id = ?" . $typeFilter;
$countParams = array_merge([$userId], $typeParams);
$totalCount = fetchValue($countQuery, $countParams);
$totalPages = ceil($totalCount / $perPage);

// Get notifications
$query = "SELECT * FROM notifications WHERE user_id = ?" . $typeFilter . " ORDER BY created_at DESC LIMIT ? OFFSET ?";
$params = array_merge([$userId], $typeParams, [$perPage, $offset]);
$notifications = fetchRows($query, $params);

// Get notification types for filter dropdown
$typesQuery = "SELECT DISTINCT type FROM notifications WHERE user_id = ? ORDER BY type";
$notificationTypes = fetchRows($typesQuery, [$userId]);

// Page title
$pageTitle = "My Notifications | GHAMECC Job Portal";

// Define base path for job portal
$basePath = "/jobs";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <style>
        .notification-item {
            transition: background-color 0.3s;
            border-left: 4px solid transparent;
        }
        .notification-item:hover {
            background-color: rgba(0,0,0,0.03);
        }
        .notification-item.unread {
            border-left-color: #0d6efd;
            background-color: rgba(13, 110, 253, 0.05);
        }
        .notification-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            margin-right: 15px;
        }
        .notification-content {
            flex: 1;
        }
        .notification-time {
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 5px;
        }
        .notification-actions {
            visibility: hidden;
        }
        .notification-item:hover .notification-actions {
            visibility: visible;
        }
        .empty-state {
            text-align: center;
            padding: 50px 0;
        }
        .empty-state i {
            font-size: 4rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php 
    if (file_exists(__DIR__ . '/includes/job-portal-navbar.php')) {
        include __DIR__ . '/includes/job-portal-navbar.php';
    } else {
        include 'includes/job-portal-navbar.php';
    }
    ?>
    
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="mb-0">My Notifications</h1>
            
            <div class="d-flex">
                <!-- Filter dropdown -->
                <div class="dropdown me-2">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="filterDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-filter me-2"></i> Filter
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="filterDropdown">
                        <li><a class="dropdown-item <?php echo empty($type) ? 'active' : ''; ?>" href="notifications.php">All Notifications</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <?php foreach ($notificationTypes as $notificationType): ?>
                            <li>
                                <a class="dropdown-item <?php echo $type === $notificationType['type'] ? 'active' : ''; ?>" 
                                   href="notifications.php?type=<?php echo urlencode($notificationType['type']); ?>">
                                    <?php 
                                    switch ($notificationType['type']) {
                                        case 'new_rating':
                                            echo '<i class="fas fa-star me-2 text-warning"></i> Ratings';
                                            break;
                                        case 'new_review':
                                            echo '<i class="fas fa-comment me-2 text-info"></i> Reviews';
                                            break;
                                        case 'job_application':
                                            echo '<i class="fas fa-file-alt me-2 text-primary"></i> Job Applications';
                                            break;
                                        case 'application_status':
                                            echo '<i class="fas fa-check-circle me-2 text-success"></i> Application Updates';
                                            break;
                                        case 'new_job':
                                            echo '<i class="fas fa-briefcase me-2 text-secondary"></i> New Jobs';
                                            break;
                                        default:
                                            echo '<i class="fas fa-bell me-2"></i> ' . ucfirst(str_replace('_', ' ', $notificationType['type']));
                                    }
                                    ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                
                <!-- Actions dropdown -->
                <div class="dropdown">
                    <button class="btn btn-outline-primary dropdown-toggle" type="button" id="actionsDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-cog me-2"></i> Actions
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="actionsDropdown">
                        <li>
                            <form method="post" action="notifications.php<?php echo !empty($type) ? '?type=' . urlencode($type) : ''; ?>">
                                <input type="hidden" name="action" value="mark_all_read">
                                <button type="submit" class="dropdown-item" onclick="return confirm('Mark all notifications as read?')">
                                    <i class="fas fa-check-double me-2"></i> Mark All as Read
                                </button>
                            </form>
                        </li>
                        <li>
                            <form method="post" action="notifications.php<?php echo !empty($type) ? '?type=' . urlencode($type) : ''; ?>">
                                <input type="hidden" name="action" value="delete_all">
                                <button type="submit" class="dropdown-item text-danger" onclick="return confirm('Are you sure you want to delete all notifications? This action cannot be undone.')">
                                    <i class="fas fa-trash me-2"></i> Delete All
                                </button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        
        <!-- Notifications List -->
        <?php if (empty($notifications)): ?>
            <div class="card">
                <div class="card-body empty-state">
                    <i class="fas fa-bell-slash"></i>
                    <h4>No Notifications</h4>
                    <p class="text-muted">
                        <?php if (!empty($type)): ?>
                            You don't have any <?php echo str_replace('_', ' ', $type); ?> notifications.
                            <br><a href="notifications.php">View all notifications</a>
                        <?php else: ?>
                            You don't have any notifications at the moment.
                        <?php endif; ?>
                    </p>
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="list-group list-group-flush">
                    <?php foreach ($notifications as $notification): ?>
                        <div class="list-group-item notification-item <?php echo $notification['is_read'] == 0 ? 'unread' : ''; ?>" data-id="<?php echo $notification['id']; ?>">
                            <div class="d-flex align-items-center">
                                <!-- Notification Icon -->
                                <div class="notification-icon 
                                    <?php 
                                    switch ($notification['type']) {
                                        case 'new_rating':
                                            echo 'bg-warning';
                                            break;
                                        case 'new_review':
                                            echo 'bg-info';
                                            break;
                                        case 'job_application':
                                            echo 'bg-primary';
                                            break;
                                        case 'application_status':
                                            echo 'bg-success';
                                            break;
                                        case 'new_job':
                                            echo 'bg-secondary';
                                            break;
                                        default:
                                            echo 'bg-secondary';
                                    }
                                    ?>">
                                    <?php 
                                    switch ($notification['type']) {
                                        case 'new_rating':
                                            echo '<i class="fas fa-star"></i>';
                                            break;
                                        case 'new_review':
                                            echo '<i class="fas fa-comment"></i>';
                                            break;
                                        case 'job_application':
                                            echo '<i class="fas fa-file-alt"></i>';
                                            break;
                                        case 'application_status':
                                            echo '<i class="fas fa-check-circle"></i>';
                                            break;
                                        case 'new_job':
                                            echo '<i class="fas fa-briefcase"></i>';
                                            break;
                                        default:
                                            echo '<i class="fas fa-bell"></i>';
                                    }
                                    ?>
                                </div>
                                
                                <!-- Notification Content -->
                                <div class="notification-content">
                                    <div class="notification-text">
                                        <?php echo htmlspecialchars($notification['message']); ?>
                                    </div>
                                    <div class="notification-time">
                                        <?php echo timeAgo($notification['created_at']); ?>
                                    </div>
                                </div>
                                
                                <!-- Notification Actions -->
                                <div class="notification-actions">
                                    <?php if ($notification['is_read'] == 0): ?>
                                        <form method="post" action="notifications.php<?php echo !empty($type) ? '?type=' . urlencode($type) : ''; ?>" class="d-inline">
                                            <input type="hidden" name="action" value="mark_read">
                                            <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-secondary" title="Mark as Read">
                                                <i class="fas fa-check"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <form method="post" action="notifications.php<?php echo !empty($type) ? '?type=' . urlencode($type) : ''; ?>" class="d-inline">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete" onclick="return confirm('Are you sure you want to delete this notification?')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                    
                                    <?php if (!empty($notification['link'])): ?>
                                        <a href="<?php echo htmlspecialchars($notification['link']); ?>" class="btn btn-sm btn-outline-primary" title="View Details">
                                            <i class="fas fa-external-link-alt"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="d-flex justify-content-center mt-4">
                    <nav aria-label="Notifications pagination">
                        <ul class="pagination">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1<?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?>" aria-label="First">
                                        <span aria-hidden="true">&laquo;&laquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $startPage = max(1, $page - 2);
                            $endPage = min($totalPages, $page + 2);
                            
                            for ($i = $startPage; $i <= $endPage; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $totalPages; ?><?php echo !empty($type) ? '&type=' . urlencode($type) : ''; ?>" aria-label="Last">
                                        <span aria-hidden="true">&raquo;&raquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>GHAMECC Job Portal</h5>
                    <p class="text-muted">Connecting talent with opportunities within the GHAMECC community.</p>
                </div>
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>Quick Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-decoration-none text-muted">Home</a></li>
                        <li><a href="job-listings.php" class="text-decoration-none text-muted">Job Listings</a></li>
                        <li><a href="talent-showcase.php" class="text-decoration-none text-muted">Talent Showcase</a></li>
                        <li><a href="categories.php" class="text-decoration-none text-muted">Categories</a></li>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h5>Contact</h5>
                    <address class="text-muted">
                        <i class="fas fa-map-marker-alt me-2"></i> GHAMECC Headquarters<br>
                        <i class="fas fa-phone me-2"></i> (123) 456-7890<br>
                        <i class="fas fa-envelope me-2"></i> jobs@ghamecc.org
                    </address>
                </div>
            </div>
            <hr class="my-4 bg-secondary">
            <div class="text-center text-muted">
                <small>&copy; <?php echo date('Y'); ?> GHAMECC Job Portal. All rights reserved.</small>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- JavaScript for notification interactions -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Mark notification as read when clicked on the link
        document.querySelectorAll('.notification-item').forEach(function(item) {
            if (item.querySelector('a')) {
                item.querySelector('a').addEventListener('click', function() {
                    const notificationId = item.dataset.id;
                    if (notificationId) {
                        fetch('ajax/mark_notification_read.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: 'notification_id=' + notificationId
                        });
                    }
                });
            }
        });
    });
    </script>
</body>
</html>
