<?php
// Guard and session
define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/Notification.php';
require_once __DIR__ . '/middleware/SecurityMiddleware.php';

// Set headers
header('Content-Type: application/json');
// Dynamic origin for credentials
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, X-API-KEY');
header('Access-Control-Allow-Credentials: true');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Initialize database connection
try {
    $pdo = Database::getInstance()->getConnection();
    $notification = new Notification($pdo);
    
    // Check if request method is POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Method not allowed', 405);
    }
    
    // Require admin authentication
    requireAdmin(true);
    
    // Get request data
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $requiredFields = ['type', 'title', 'message'];
    foreach ($requiredFields as $field) {
        if (empty($data[$field])) {
            throw new Exception("Missing required field: $field", 400);
        }
    }
    
    // Validate notification type
    $validTypes = ['info', 'alert', 'warning', 'success'];
    if (!in_array($data['type'], $validTypes)) {
        throw new Exception('Invalid notification type', 400);
    }
    
    // Prepare notification data
    $notificationData = [
        'user_id' => $data['user_id'] ?? null, // null for system-wide notifications
        'type' => $data['type'],
        'title' => $data['title'],
        'message' => $data['message']
    ];
    
    // Create notification
    $notificationId = $notification->create($notificationData);
    
    if (!$notificationId) {
        throw new Exception('Failed to create notification', 500);
    }
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Notification sent successfully',
        'notification_id' => $notificationId
    ]);
    
} catch (Exception $e) {
    http_response_code($e->getCode() ?: 500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'code' => $e->getCode()
    ]);
}
