<?php
/**
 * API endpoint to create a notification
 * 
 * POST Parameters:
 * - title: Notification title
 * - message: Notification message
 * - type: Notification type
 * - priority: Notification priority
 * - target_audience: Target audience ('all', 'admins', 'members', 'specific')
 * - specific_recipients: Array of specific recipient IDs (only if target_audience is 'specific')
 * - expires_at: Optional expiration date
 * - related_entity_type: Optional related entity type
 * - related_entity_id: Optional related entity ID
 * - metadata: Optional additional data (JSON)
 */

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

use Services\Notification\NotificationService;

// Require admin access for creating notifications
requireAdmin();

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Method not allowed';
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

try {
    // Get POST data
    $postData = json_decode(file_get_contents('php://input'), true);
    if (!$postData) {
        $postData = $_POST;
    }
    
    // Validate required fields
    $requiredFields = ['title', 'message', 'type', 'priority', 'target_audience'];
    foreach ($requiredFields as $field) {
        if (!isset($postData[$field]) || empty($postData[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    // Validate target audience
    $validAudiences = ['all', 'admins', 'members', 'specific'];
    if (!in_array($postData['target_audience'], $validAudiences)) {
        throw new Exception("Invalid target audience. Must be one of: " . implode(', ', $validAudiences));
    }
    
    // If target audience is 'specific', require specific_recipients
    if ($postData['target_audience'] === 'specific' && 
        (!isset($postData['specific_recipients']) || empty($postData['specific_recipients']))) {
        throw new Exception("Field 'specific_recipients' is required when target_audience is 'specific'");
    }
    
    // Get current admin ID
    $adminId = $_SESSION['admin_id'] ?? 0;
    
    // Prepare notification data
    $notificationData = [
        'title' => $postData['title'],
        'message' => $postData['message'],
        'type' => $postData['type'],
        'priority' => $postData['priority'],
        'target_audience' => $postData['target_audience'],
        'created_by' => $adminId
    ];
    
    // Add optional fields if provided
    if (isset($postData['specific_recipients'])) {
        $notificationData['specific_recipients'] = $postData['specific_recipients'];
    }
    
    if (isset($postData['expires_at'])) {
        $notificationData['expires_at'] = $postData['expires_at'];
    }
    
    if (isset($postData['related_entity_type'])) {
        $notificationData['related_entity_type'] = $postData['related_entity_type'];
    }
    
    if (isset($postData['related_entity_id'])) {
        $notificationData['related_entity_id'] = $postData['related_entity_id'];
    }
    
    if (isset($postData['metadata'])) {
        $notificationData['metadata'] = $postData['metadata'];
    }
    
    // Create notification
    $notificationService = new NotificationService();
    $result = $notificationService->createNotification($notificationData);
    
    // Set response
    $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;
