<?php
/**
 * API endpoint to list notifications
 * 
 * This endpoint returns all notifications with pagination and filtering
 * 
 * GET Parameters:
 * - user_id: User ID (required for user-specific notifications)
 * - user_type: User type ('admin' or 'member', required for user-specific notifications)
 * - type: Filter by notification type (optional)
 * - priority: Filter by priority (optional)
 * - is_read: Filter by read status (0/1, optional)
 * - search: Search in title and message (optional)
 * - page: Page number for pagination (default: 1)
 * - limit: Limit results (default: 10)
 */

// 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,
    'data' => [],
    'message' => 'Error retrieving notifications'
];

try {
    // Get parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;
    
    // Check if we're getting user-specific notifications
    $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : null;
    $userType = isset($_GET['user_type']) ? $_GET['user_type'] : null;
    
    // Build filters
    $filters = [];
    
    if (isset($_GET['type']) && !empty($_GET['type'])) {
        $filters['type'] = $_GET['type'];
    }
    
    if (isset($_GET['priority']) && !empty($_GET['priority'])) {
        $filters['priority'] = $_GET['priority'];
    }
    
    if (isset($_GET['is_read']) && ($_GET['is_read'] === '0' || $_GET['is_read'] === '1')) {
        $filters['is_read'] = (int)$_GET['is_read'];
    }
    
    if (isset($_GET['search']) && !empty($_GET['search'])) {
        $filters['search'] = $_GET['search'];
    }
    
    // Create notification service
    $notificationService = new NotificationService();
    
    // Get notifications based on whether we have user info or not
    if ($userId !== null && $userType !== null && in_array($userType, ['admin', 'member'])) {
        // Get user-specific notifications
        $result = $notificationService->getNotifications($userId, $userType, $filters, $limit, $offset);
        $response = $result;
    } else {
        // Get all notifications (admin view)
        // Check if user is admin
        requireAdmin();
        
        // Call the getAllNotifications method
        $result = $notificationService->getAllNotifications($filters, $limit, $offset);
        $response = $result;
    }
    
} catch (PDOException $e) {
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    $response['message'] = 'Error: ' . $e->getMessage();
}

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