<?php
/**
 * API: Get recent notifications for current user
 * 
 * This endpoint returns recent unread notifications for the current user
 * It's used in the navbar dropdown and for real-time notifications
 */

require_once '../../config/database.php';
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => [],
    'message' => 'Error retrieving notifications'
];

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    $userId = $_SESSION['admin_id']; // Get from session
    $userType = 'admin';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    
    // Get unread notifications for this user
    $query = "SELECT 
                n.id, n.type, n.title, n.message, n.priority, n.created_at,
                CONCAT(a.first_name, ' ', a.last_name) as created_by_name,
                nr.is_read, nr.read_at
              FROM notifications n
              JOIN notification_recipients nr ON n.id = nr.notification_id
              LEFT JOIN admins a ON n.created_by = a.id
              WHERE nr.user_id = :user_id 
              AND nr.user_type = :user_type
              ORDER BY n.created_at DESC
              LIMIT :limit";
    
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':user_id', $userId);
    $stmt->bindValue(':user_type', $userType);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Count unread notifications
    $countQuery = "SELECT COUNT(*) as unread_count
                  FROM notification_recipients
                  WHERE user_id = :user_id 
                  AND user_type = :user_type
                  AND is_read = 0";
    
    $countStmt = $conn->prepare($countQuery);
    $countStmt->bindValue(':user_id', $userId);
    $countStmt->bindValue(':user_type', $userType);
    $countStmt->execute();
    
    $unreadCount = $countStmt->fetch(PDO::FETCH_ASSOC)['unread_count'];
    
    // Format the response
    $response = [
        'success' => true,
        'data' => [
            'notifications' => $notifications,
            'unread_count' => $unreadCount
        ],
        'message' => 'Recent notifications retrieved successfully'
    ];
    
} 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;
