<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized access']);
    exit;
}

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $title = $_POST['title'] ?? '';
    $message = $_POST['message'] ?? '';
    $type = $_POST['type'] ?? 'info';
    $recipients = $_POST['recipients'] ?? [];
    $priority = $_POST['priority'] ?? 'normal';
    $send_email = isset($_POST['send_email']) ? (bool)$_POST['send_email'] : false;
    
    if (empty($title) || empty($message)) {
        throw new Exception('Title and message are required');
    }
    
    // Insert notification
    $stmt = $pdo->prepare("
        INSERT INTO notifications (title, message, type, priority, created_by, created_at) 
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$title, $message, $type, $priority, $_SESSION['user_id']]);
    $notificationId = $pdo->lastInsertId();
    
    // Handle recipients
    if (!empty($recipients)) {
        if (in_array('all', $recipients)) {
            // Send to all active members
            $stmt = $pdo->prepare("
                INSERT INTO notification_recipients (notification_id, user_id, created_at)
                SELECT ?, id, NOW() FROM members WHERE status = 'approved'
            ");
            $stmt->execute([$notificationId]);
        } else {
            // Send to specific recipients
            $stmt = $pdo->prepare("
                INSERT INTO notification_recipients (notification_id, user_id, created_at) 
                VALUES (?, ?, NOW())
            ");
            foreach ($recipients as $userId) {
                $stmt->execute([$notificationId, $userId]);
            }
        }
    }
    
    // Send email notifications if requested
    if ($send_email && !empty($recipients)) {
        // This would integrate with your email service
        // For now, just log that emails should be sent
        error_log("Email notification requested for notification ID: $notificationId");
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Notification created successfully',
        'notification_id' => $notificationId
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to create notification: ' . $e->getMessage()]);
}
?>
