<?php
require_once '../config/config.php';
requireLogin('candidate');
require_once '../includes/notification_system.php';

$database = new Database();
$db = $database->getConnection();
$notificationSystem = new NotificationSystem($db);

$candidate_id = $_SESSION['candidate_id'];
$message = '';

// Handle mark as read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_read'])) {
    $notification_id = (int)$_POST['notification_id'];
    if ($notificationSystem->markAsRead($notification_id, 'candidate', $candidate_id)) {
        $message = 'Notification marked as read.';
    }
}

// Handle mark all as read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_all_read'])) {
    $stmt = $db->prepare("UPDATE notifications SET is_read = TRUE WHERE user_type = 'candidate' AND user_id = ?");
    if ($stmt->execute([$candidate_id])) {
        $message = 'All notifications marked as read.';
    }
}

// Get filter
$filter = $_GET['filter'] ?? 'all';
$unread_only = ($filter === 'unread');

// Get notifications
$notifications = $notificationSystem->getUserNotifications('candidate', $candidate_id, 50, $unread_only);
$unread_count = $notificationSystem->getUnreadCount('candidate', $candidate_id);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .notification-item {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }
        .notification-item.unread {
            background-color: #f8f9fa;
            border-left-color: #0d6efd;
        }
        .notification-item:hover {
            background-color: #f1f3f4;
        }
        .notification-icon {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        .notification-icon.info { background: rgba(13, 110, 253, 0.1); color: #0d6efd; }
        .notification-icon.success { background: rgba(25, 135, 84, 0.1); color: #198754; }
        .notification-icon.warning { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        .notification-icon.error { background: rgba(220, 53, 69, 0.1); color: #dc3545; }
        .time-ago {
            font-size: 0.75rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['candidate_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-user me-2"></i>Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-search me-2"></i>Browse Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>My Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="notifications.php">
                                <i class="fas fa-bell me-2"></i>Notifications
                                <?php if ($unread_count > 0): ?>
                                    <span class="badge bg-danger ms-2"><?php echo $unread_count; ?></span>
                                <?php endif; ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-bell me-2"></i>Notifications
                            <?php if ($unread_count > 0): ?>
                                <span class="badge bg-primary ms-2"><?php echo $unread_count; ?> unread</span>
                            <?php endif; ?>
                        </h1>
                    </div>

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

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

                    <!-- Actions -->
                    <?php if ($unread_count > 0): ?>
                        <div class="mb-3">
                            <form method="POST" class="d-inline">
                                <button type="submit" name="mark_all_read" class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-check-double me-1"></i>Mark All as Read
                                </button>
                            </form>
                        </div>
                    <?php endif; ?>

                    <!-- Notifications List -->
                    <div class="card">
                        <div class="card-body p-0">
                            <?php if (empty($notifications)): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-bell-slash fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No notifications found</h5>
                                    <p class="text-muted">
                                        <?php echo $filter === 'unread' ? 'You have no unread notifications.' : 'You haven\'t received any notifications yet.'; ?>
                                    </p>
                                </div>
                            <?php else: ?>
                                <?php foreach ($notifications as $notification): ?>
                                    <div class="notification-item p-3 border-bottom <?php echo !$notification['is_read'] ? 'unread' : ''; ?>">
                                        <div class="d-flex">
                                            <div class="me-3">
                                                <div class="notification-icon <?php echo $notification['type']; ?>">
                                                    <i class="fas fa-<?php echo getNotificationIcon($notification['type'], $notification['related_type']); ?>"></i>
                                                </div>
                                            </div>
                                            <div class="flex-grow-1">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <h6 class="mb-1 <?php echo !$notification['is_read'] ? 'fw-bold' : ''; ?>">
                                                            <?php echo htmlspecialchars($notification['title']); ?>
                                                        </h6>
                                                        <p class="mb-1 text-muted">
                                                            <?php echo htmlspecialchars($notification['message']); ?>
                                                        </p>
                                                        <div class="time-ago">
                                                            <i class="fas fa-clock me-1"></i>
                                                            <?php echo timeAgo($notification['created_at']); ?>
                                                        </div>
                                                    </div>
                                                    <div class="d-flex flex-column align-items-end">
                                                        <?php if (!$notification['is_read']): ?>
                                                            <form method="POST" class="mb-2">
                                                                <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                                                <button type="submit" name="mark_read" class="btn btn-sm btn-outline-primary">
                                                                    <i class="fas fa-check"></i>
                                                                </button>
                                                            </form>
                                                        <?php endif; ?>
                                                        
                                                        <?php if ($notification['related_type'] === 'application' && $notification['related_id']): ?>
                                                            <a href="applications.php" class="btn btn-sm btn-link">
                                                                <i class="fas fa-external-link-alt"></i>
                                                            </a>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<?php
function getNotificationIcon($type, $related_type) {
    if ($related_type === 'application') {
        switch ($type) {
            case 'success': return 'check-circle';
            case 'warning': return 'exclamation-triangle';
            case 'error': return 'times-circle';
            default: return 'file-alt';
        }
    }
    
    switch ($type) {
        case 'success': return 'check';
        case 'warning': return 'exclamation';
        case 'error': return 'times';
        default: return 'info';
    }
}

function timeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return 'Just now';
    } elseif ($diff < 3600) {
        $minutes = floor($diff / 60);
        return $minutes . ' minute' . ($minutes > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 2592000) {
        $days = floor($diff / 86400);
        return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    } else {
        return date('M j, Y', $time);
    }
}
?>