<?php
/**
 * API endpoint to mark a notification as read
 * 
 * POST Parameters:
 * - notification_id: ID of the notification
 * - user_id: ID of the user
 * - user_type: Type of the user ('admin' or 'member')
 */

// Include dependencies
require_once '../../config/database.php';
require_once '../../config/auth_enhanced.php';
require_once '../../services/notification/NotificationService.php';

use Services\Notification\NotificationService;

// Check if user is authenticated
checkAuthentication();

// Default response structure
$response = [
    'success' => false,
    'message' => 'Error marking notification as read'
];

// Handle request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Get POST data
        $postData = json_decode(file_get_contents('php://input'), true);
        
        // If POST data is empty, try regular POST
        if (empty($postData)) {
            $postData = $_POST;
        }
        
        // Validate required fields
        $requiredFields = ['notification_id', 'user_id', 'user_type'];
        foreach ($requiredFields as $field) {
            if (!isset($postData[$field]) || empty($postData[$field])) {
                throw new Exception("Field '$field' is required");
            }
        }
        
        // Validate user type
        if (!in_array($postData['user_type'], ['admin', 'member'])) {
            throw new Exception("Invalid user type. Must be 'admin' or 'member'");
        }
        
        // Get notification ID and user info
        $notificationId = (int)$postData['notification_id'];
        $userId = (int)$postData['user_id'];
        $userType = $postData['user_type'];
        
        // Create notification service
        $notificationService = new NotificationService();
        
        // Mark notification as read
        $result = $notificationService->markAsRead($notificationId, $userId, $userType);
        
        // Return response
        $response = $result;
        
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
} else {
    // Method not allowed
    http_response_code(405);
    $response['message'] = 'Method not allowed. Use POST.';
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
