<?php
/**
 * Get Notification API Endpoint
 * 
 * Retrieves a single notification by ID
 */

// Initialize the session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include database connection
require_once __DIR__ . '/../../config/db_connect.php';

// Check authentication
if (!isset($_SESSION['admin_id'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Authentication required'
    ]);
    exit;
}

$admin_id = $_SESSION['admin_id'];

// Check if notification ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Notification ID is required'
    ]);
    exit;
}

$notification_id = intval($_GET['id']);

try {
    // Get notification details
    $query = "
        SELECT n.*, a.username as created_by_name
        FROM notifications n
        LEFT JOIN admin_users a ON n.created_by = a.id
        INNER JOIN notification_recipients nr ON nr.notification_id = n.id
        WHERE n.id = ? AND nr.recipient_id = ? AND nr.recipient_type = 'admin'
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param('ii', $notification_id, $admin_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Notification not found or you do not have permission to view it'
        ]);
        exit;
    }
    
    $notification = $result->fetch_assoc();
    
    // Return notification
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'data' => $notification
    ]);
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving notification: ' . $e->getMessage()
    ]);
}
